I have an app try to use provider for add product to card ,first I have this product model :
class Products {
final String item;
final int price;
Products({this.item, this.price});
}
then I have this Widget to view the list of products ,and it is show successfully :
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);
},
),
),
);
}),
);
}
}
also I have this provier :
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();
}
}
I get this error when I pressed on button :
The method 'add' was called on null.
Receiver: null
Tried calling: add(Instance of 'MyProducts')