Search code examples
flutterdartflutter-freezed

Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<X>


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:

enter image description here

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}:

enter image description here


Solution

  • 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