1

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')

How can I fix it ?

8

You have not actually created a List yet.

Change

List<MyProducts> product;

to this

List<MyProducts> product = [];
1

The issue here is the line

List<MyProducts> product;

when you just declare a variable(of any data-type) just stores null inside of it. And null does not have add to insert the elements in the list.

So instead of declaring initialize it with empty list like

List<MyProducts> product = [];

or

List<MyProducts> product = List<MyProducts>();

0

You need to 'create' the list before you can add something to it. You can do so by changing

 List<MyProducts> product; 

to

 List<MyProducts> product = List<MyProducts>();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.