Flutter Class 'Productlist' 没有实例方法 '[]'。接收者:'Productlist' 的实例尝试调用:[]("price")

Flutter Class 'Productlist' has no instance method '[]'. Receiver: Instance of 'Productlist' Tried calling: []("price")

我有一个问题,我想将 MAY DATA PROVIDER 结果放入列表中。为了过滤数据,我想将其转换为列表。 这是错误的结果:


I/flutter (32434): [Instance of 'Productlist', Instance of 'Productlist', Instance of 'Productlist', Instance of 'Productlist', Instance of 'Productlist', Instance of 'Productlist', Instance of 'Productlist', Instance of 'Productlist', Instance of 'Productlist', Instance of 'Productlist', Instance of 'Productlist', Instance of 'Productlist', Instance of 'Productlist', Instance of 'Productlist', Instance of 'Productlist']

这是我使用这段代码后的错误:


 productfiltered = productdata.where((productx) => productx['price'] == '2000').toList();


════════ Exception caught by widgets library ═══════════════════════════════════
Class 'Productlist' has no instance method '[]'.
Receiver: Instance of 'Productlist'
Tried calling: []("price")

这是我的代码:


class FeaturedCard2 extends StatelessWidget {

  @override

  Widget build(BuildContext context) {
    
List productdata = [];
    
List productfiltered = [];

    final products = Provider.of<List<Productlist>>(context);

    productdata = products;
    productfiltered = productdata;

    print(productfiltered);
    productfiltered = productdata.where((productx) => productx['price'] == '2000').toList();

    return Container();
  }
}

this is the image

我想要这样的结果:


 [{productname: numarkxx, qty: 2, price: 1000,productname: numarkxx, qty: 2, price: 1000, productname: numarkxx, qty: 2, price: 1000}]

您的产品型号 class 将如下所示:


class ProductModel {
  String productname;
  int qty;
  int price;

  ProductModel({this.productname, this.qty, this.price});

  ProductModel.fromJson(Map<String, dynamic> json) {
    productname = json['productname'];
    qty = json['qty'];
    price = json['price'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['productname'] = this.productname;
    data['qty'] = this.qty;
    data['price'] = this.price;
    return data;
  }
}

然后,您无需定义任何不必要的 productdata 变量。您可以像这样简单地检查和过滤价格数组:


class FeaturedCard2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    List productfiltered = [];

    final products = Provider.of<List<ProductModel>>(context);

    productfiltered = products;

    print(productfiltered);
    productfiltered =
        products.where((productx) => productx.price == 2000).toList(); // Here is important!

    return Container();
  }
}