Search code examples
flutterdartflutter-provider

List is emptied after notifyListeners


I've got a weird one, I've been scratching my head for a while

I have a property on one of my classes using provider I can access and modify just fine except for this particular scenario:

I add a product to the _products list

_products.add(product);
notifyListeners();

At this point product is a class with the following properties

name String;
id String;
ingredients List<String>;

let's say for example product is

final product = Product(name:'milk', id:1, ingredients:['milk']);

This element gets added to the List and I can see in debugging that now _products is indeed a list with 1 item inside and all properties are correct

Once it notifies listeners they get the new value of _products and I can see that they receive the new value just fine except that for some odd reason the ingredients list is empty!

[ Product(name:'milk', id:1, ingredients:[]) ] // _products for representation purposes

I just verified the value of _products before notifying and it had the ingredients property correctly then right after notifying, that property becomes an empty list The other 2 properties id and name are updated correctly

I have checked very thoroughly and I have no code to modify _products else where


Solution

  • Sorry all, this wasn't a problem regarding provider at all

    What happened is that when I was assigning the product to the products list, the list of ingredients was a reference which was cleared by the controller after using it, so in code it was something like this:

    
    List<String> ingredients = [];
    
    void onAddIngredient(){
      ingredients.add(ingredientController.text);
    }
    
    void onSubmit(){
    
      final myNewProduct = Product(
        name: nameController.text,
        id: idController.text, 
        ingredients:ingredients
      )
    
      providerAction(myNewProduct); // This is where it gets added to _products
    
      nameController.clear();
      idController.clear();
      ingredientController.clear();
      ingredients.clear(); // This was the problem where I was deleting the reference 
    }