About changing list inside a list

I just read chapter 12, the part about shallow copy and deep copy. I just want to write some code to illustrate this. My code as follows:

  var a = [
    [1, 2],
  var b = List.of(a);

I have error on the line b[0].add(3). Could anyone tell me why this error occur and the fix to it?

1 Like

The Dart analyzer gives the following error message for that line:

The method 'add' isn't defined for the type 'Object'.

You mixed two different types in your a-list. The type of the first element is List<int> and the types of the next two elements are int. Since your a list contains mixed types, Dart infers the type contained in your a-list to be Object, which is the nearest common supertype of int and List.

Your b-list is a copy of your a-list, so it is also the same type, that is, List<Object>.

When you call b[0], you are accessing the first element of the b-list. The only thing Dart knows about this first element is that it is of type Object. You can’t add anything to an Object, so Dart gives you an error. You know that it is actually a list, but Dart doesn’t know that.

You can fix the error by telling Dart the type. Do this by downcasting Object to List<int> using the as keyword, like so:

(b[0] as List<int>).add(3); 

The error disappears.


Thank you. @suragch Now I can using to illustrate what is shallow copy. Thank you for pointing out my mistake. I am really not aware of this. May be I come from experience in duck typing language like Python.