Flutter:在null上调用了方法“add”
我有一个应用程序尝试使用提供程序将产品添加到卡中,首先我有这个产品型号:
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')
我该如何解决?
回答
You have not actually created a List yet.
Change
List<MyProducts> product;
to this
List<MyProducts> product = [];