list - flutter : The method 'add' was called on null

标签 list flutter model provider

我有一个应用程序尝试使用提供商将产品添加到卡中,首先我有这个产品模型:

class Products {
  final String item;
  final int price;    
  Products({this.item, this.price});
}

然后我有这个小部件来查看产品列表,它显示成功:

import './service/provider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';    
import 'models/products.dart';    
class ProductList extends StatelessWidget {
  @override
  List<Products> myProducList;
  Widget build(BuildContext context) {
    myProducList = [
      Products(item: 'Car', price: 20000),
      Products(item: 'PC', price: 500),
      Products(item: 'LapTop', price: 750),
      Products(item: 'House', price: 25000),
    ];
    return Scaffold(
      body: ListView.builder(
          shrinkWrap: true,
          itemCount: myProducList.length,
          itemBuilder: (context, index) {
            return Card(
              child: ListTile(
                title: Text(myProducList[index].item),
                subtitle: Text(myProducList[index].price.toString()),
                trailing: IconButton(
                  icon: Icon(Icons.add),
                  onPressed: () {
                    Provider.of<MyProv>(context, listen: false).add_item(
                    myItem: myProducList[index].item,
                    myPrice: myProducList[index].price);
                  },
                ),
              ),
            );
          }),
    );
  }
}

我也有这个供应商:

class MyProducts {
  final String item;
  final int price;

  MyProducts({this.item, this.price});
}

class MyProv with ChangeNotifier {
  List<MyProducts> product;

  void add_item({String myItem, int myPrice}) {
    product.add(MyProducts(
      item: myItem,
      price: myPrice,
    ));
    notifyListeners();
  }
    }

按下按钮时出现此错误:

The method 'add' was called on null.
Receiver: null
Tried calling: add(Instance of 'MyProducts')

我该如何解决?

最佳答案

您还没有真正创建一个列表。

改变

List<MyProducts> product;

对此

List<MyProducts> product = [];

关于list - flutter : The method 'add' was called on null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65144596/

相关文章:

Python 扩展切片与列表 : is the documentation correct?

python - 有没有办法循环索引

python - 最好的方法是根据元组的第一个元素重新排列元组列表以匹配字符串?

python - Django 中的类别、子类别和产品

mysql - 如何从 Rails 2 中不包含特定项目的多对多关系中选择特定记录?

c# - 检查项目是否不在键值对列表中

dart - Flutter - ListView.builder 尺寸非常大并且不会改变

flutter - 帖子请求中的null调用了getter 'length'

flutter : Show an Alert Dialog after an async Api call

service - 如何存储 Symfony2 实体中使用的修饰符