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?
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)`
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