Shouldn't we be able to assign a value to a field IF IT IS THE SAME TYPE UNDER THE HOOD - E.G. IN THE DEBUGGER IT SAYS IT IS A List<GroceryItmTag>? and you are trying to assign it to a List<GroceryItmTag>?, and just cast it to the correct type or to dynamic? Here I am hovering over formFieldValue, which I later assign to groceryItm.tags:
groceryItem.tags is List<GroceryItmTag>? and I'm assigning to it, a field which is a List<GroceryItmTag>?, under the hood, even though it is not recognised as that. But it is throwing this exception whether I cast it as List<GroceryItmTag>? or I just cast it to dynamic and assign it.
Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<GroceryItmTag>?'
How can I assign it without throwing the exception?
This is hovering over groceryItm.tags, the field that I am trying to assign formFieldValue to {List<GroceryItmTag>? tags}:
CodePudding user response:
Shouldn't we be able to assign a value to a field if it is the same type under the hood, and just cast it to the correct type or to dynamic?
No
Simple example. If I have a List<Sheep> and I assign it to a List<dynamic>, now you could suddenly insert a Wolf() into my List<Sheep> through that List<dynamic> variable. Because a Wolf is a dynamic, too and you can insert into a List<dynamic>. That is why it does not work and will not work.
You could assign your List<Sheep> to a plain dynamic though and cast it as neccessary.
CodePudding user response:
A workaround is to filter on the type and assign that. Example:
List<dynamic> list = ['a', 'b', 'c'];
List<String> stringList = list as List<String>; //this will give a runtime error
List<String> stringList = list.whereType<String>().toList(); //workaround


