MarcS82
MarcS82

Reputation: 2517

Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<String>' in type cast

This exception is thrown in the lins myList = results['users'];. I also tried myList = results['users'] as List<String>;. The type of results['users'] is List<dynamic>. Actually it contains Strings so why can't it be converted?

List<String> myList = List<String>();
results = await ApiService.searchUser();
setState(() {
  myList = results['users'];
}

Upvotes: 9

Views: 11681

Answers (1)

Lesiak
Lesiak

Reputation: 25936

You can build a new list

myList = new List<String>.from(results['users']);

or alternatively, use a cast:

myList = results['users'].cast<String>();

Note that myList.runtimeType will differ:

  • List<String> in case of a new list
  • CastList<dynamic, String> in case of a cast

See discussion on Effective Dart: When to use "as", ".retype", ".cast"

I would suggest that you hardly ever use cast or retype.

  • retype wraps the list, forcing an as T check for every access, needed or not.
  • cast optionally wraps the list, avoiding the as T checks when not needed, but this comes at a cost of making the returned object polymorphic (the original type or the CastList), which interferes with the quality of the code that can be generated.

If you are going to touch every element of the list, you might as well copy it with

 new List<T>.from(original)

So I would only use cast or retype if my access patterns are sparse or if I needed to update the original.

Note that the discussion above refers to retype method, which was removed from Dart 2, but other points are still valid.

Upvotes: 26

Related Questions