0
var data = List();
snapshot.data.documents.forEach((doc) => data.add(doc.data)); //my example data is one doc
data.add({"x": "y"}); //works
data[0]["bar"].add({"foo": "bar"}); //doesn't

My data looks like this:

  data = [
    {
      "foo": "",
      "bar": [
        {"foo": "bar"},
        {"foo": "bar"},
        {"foo": "bar"},
      ],
    },
  ];

When I do the second array modification, it gives me this error:

Unhandled Exception: Unsupported operation: Cannot add to a fixed-length list

I have tried doing this with normal data that is not fetched from firebase, and it works as expected. I also tried using List.from to populate the array but it didn't work either.

3 Answers 3

2

snapshot.data.documents[0]['bar'] apparently is a fixed-length (i.e., non-growable) List. You can't make a non-growable List growable. You instead need to create a growable copy:

data[0]["bar"] = data[0]["bar"].toList(); // Create a copy.
data[0]["bar"].add({"foo": "bar"}); // Now this should work.

Alternatively:

data[0]["bar"] = [...data[0]["bar"], {"foo": "bar"}];

However, while the latter approach is more compact, it is less clear that the copy is explicitly desired.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. This was the issue. It works now. Is there any other way of fixing it by forcing the data to be growable upon adding it to the array?
0

Do like this:

var data = List();
var data2= List();

snapshot.data.documents.forEach((doc) => data.add(doc.data)); //my example data is one doc
data.add({"x": "y"}); //works

data2=data[0]["bar"];
data2.add({"foo": "bar"});

1 Comment

data2 = List() is pointless if you're just going to reassign it later, and adding the data2 variable won't change a fixed-length List to a growable one.
0

The problem is add method is used over an object type. You need to add a cast before using add method:

  (data[0]["bar"] as List<Map<String, String>>).add({"foo": "bar"});

1 Comment

I'm pretty sure the static type is dynamic. Otherwise there would probably be a different error about there not being an add method. The error message clearly indicates that the problem is that the OP is trying to modify a fixed-length List, not a growable one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.