Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter : The method 'add' was called on null

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 ?

like image 738
Sermed mayi Avatar asked Jun 13 '26 23:06

Sermed mayi


2 Answers

You have not actually created a List yet.

Change

List<MyProducts> product;

to this

List<MyProducts> product = [];
like image 147
Tomas Avatar answered Jun 15 '26 21:06

Tomas


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>();

like image 31
Balaji Venkatraman Avatar answered Jun 15 '26 21:06

Balaji Venkatraman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!