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'];
}
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 listCastList<dynamic, String>
in case of a castSee 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With