Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

flutter

dart

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'];
}
like image 414
MarcS82 Avatar asked Dec 13 '22 09:12

MarcS82


1 Answers

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.

like image 145
Lesiak Avatar answered May 24 '23 18:05

Lesiak