How to cast Object to a specified type in Flutter
8,433
Solution 1
Easiest way :
final args = ModalRoute.of(context).settings.arguments as FoodScreenArguments ;
Solution 2
Unlike java's parentheses casting (), in flutter, it uses as
keyword. Here is an example from my code where I am printing a variable of class.
debugPrint("rht: List size ${((albumList1.first) as AlbumData).title}");
Solution 3
In cases where you are working with a collection that you don’t create, such as from JSON or an external data source, you can use the cast()
method provided by Iterable
implementations, such as List.
Map<String, dynamic> json = fetchFromExternalSource();
var names = json['names'] as List;
assumeStrings(names.cast<String>());
Author by
zoom xu
Updated on December 27, 2022Comments
-
zoom xu over 1 year
I get a linter error but don't know how to fix it
final FoodScreenArguments args = ModalRoute.of(context).settings.arguments;
A value of type
Object
can't be assigned to a variable of typeFoodScreenArguments
.Try changing the type of the variable, or casting the right-hand type to
FoodScreenArguments
. -
zoom xu about 3 yearsThanks, i followed Dude's advice and fixed it