Flutter how to use Lists to create similar widgets white implicit-case and implicity-dynamic set to false
The error "Missing type arguments for map literal. Try adding an explicit type like 'dynamic' or enable implicit dynamic in your analysis options." seems to require you to cast <String,dynamic>
on each Map entry for defineWidgets
. Though the code you've provided seems to work fine on DartPad. The declaration could look something similar to.
List<Map<String,dynamic>> pricing = [
<String, dynamic>{"name":"beer", "price": 5},
<String, dynamic>{"name":"wine", "price": 10},
];
for(Map<String,dynamic> product in pricing){
print('${product['name']} Price: ${product['price']}');
}
As for Text(defineWidgets[i]['text'])
, the Widget can only handle String value. But since we're fetching a dynamic value from Map<String, dynamic>
, we need to cast the value as a String for the Widget to know that value is indeed a String.
`Text(defineWidgets[i]['text'] as String)`
William Terrill
Updated on December 19, 2022Comments
-
William Terrill over 1 year
I'm trying to be better about typing in flutter/dart. To force this, I made an analysis_options.yaml with:
analyzer: strong-mode: implicit-casts: false implicit-dynamic: false
and that works great, but I have a hard time with code like the following:
Widget build(BuildContext context) { return Column( children: [...widgetList()]); } widgetList(){ List<Map<String,dynamic>> defineWidgets = [ {"text":"beer", "color": Colors.blue}, // <-- Missing type arguments for map literal. Try adding an explicit type like 'dynamic' or enable implicit dynamic in your analysis options. {"text":"wine", "color": Colors.red}, ]; List<Widget> finalWidgets =[]; for(int i = 0; i < defineWidgets.length; i++ ){ finalWidgets.add( Expanded(child:Container( child:Text(defineWidgets[i]['text']), // <-- the argument type 'dynamic' can't be assigned to the parameter type 'String' color:defineWidgets[i]['color'] )) ); } return finalWidgets; }
I tried using cast() to no avail. Is there a way to do this of function without setting implicit-casts and implicit-dynamic to true?
-
jamesdlin about 4 yearsThe first lint is asking you to do:
<String, dynamic>{key1: value1, key2: value2}
for each of yourMap
literals. The second is telling you to use an explicit cast (i.e.,defineWidgets[i]['text'] as String
). -
William Terrill about 4 yearsthat did the trick. Thank you!
-