'Flutter - type 'Future<dynamic>' is not a subtype of type 'List<Map<String, dynamic>>'
I am using mysql1: ^0.19.2
and trying to fetch some data from a database to display in a select_form_field (select_form_field: "^2.2.0"
). The database table I'm fetching data from contains 2 columns: 'id' and 'name' that should go as the value
and label
respectively in the List<Map<String, dynamic>>
that fills the select_form_field.
I've created a method in my database.dart that fetches the data, fills a List<Map<String, dynamic>>
and returns it. The signature of the connect()
-method looks like this Future<MySqlConnection> connect() async {...}
:
getData() async {
List<Map<String, dynamic>> items = <Map<String, dynamic>>[];
dynamic conn = await connect();
var results = conn.query('select * from data');
for (var row in results) {
items.add({'value': row[0], 'label': row[1]});
}
return items;
}
In my main.dart I want to initialize this List and feed it to my select_form_field:
class MyCustomFormState extends State<MyCustomForm> {
final List<Map<String, dynamic>> _items = getData(); // <-- Exception happens here
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
children: <Widget>[
Container(
child: SelectFormField(
controller: nameController,
hintText: "...",
items: _items, // <-- List goes here
...
}
I've tried adding helper methods without an async
signature from which I could initialize the list, but that didn't work. Other solutions I've found on StackOverflow don't seem to suit my problem.
Solution 1:[1]
You have to wait for the data to get from an async function. For example,
final List<Map<String, dynamic>> _items = getData();
should be
final List<Map<String, dynamic>> _items = await getData();
So final code should be
late List<Map<String, dynamic>> _items;
@override
void initState() {
super.initState();
_getData();
}
_getData() async {
_items = await getData();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |