Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The method 'add' was called on null

I try to parse my firebase collection and return a list of Service type. Here I have replaced my firebase call and parsing with a hard code for simplify it.

 Future<List<Service>> _getServices() async {
   List<Service> _servicesList;

      Service service = new Service(
          id: 1,
          name: "name",
          location: "location",
          description: "description",
          image: "image");
      print(service.description);
      _servicesList.add(service);
  return _servicesList;
 }

The print in the function returns the right thing but I got this error :

NoSuchMethodError: The method 'add' was called on null.

like image 879
Pierre Le Brun Avatar asked Apr 23 '19 06:04

Pierre Le Brun


1 Answers

That's because you have not initialized _servicesList

List<Service> _servicesList = List<Service>();

EDIT: List is now deprecated

Try this to create an empty list.

List<Service> _servicesList = [];

OR

To create a fixed length list of size 0.

List<Service> _serviceList = List<Service>.empty();

To create a growable list

List<Service> _serviceList = List<Service>.empty(growable: true);

Refer docs for more details on constructors.

like image 199
Mangaldeep Pannu Avatar answered Sep 18 '22 17:09

Mangaldeep Pannu