Been coding in dart for a few months now. Currently trying to generate a grid view that contains titles from a a local SQL database. I am able to go through the database and save the titles to an array for later use. I am able to print them out no problem but when I try to display them in my grid view I get "type 'Future' is not a subtype of type 'String'" The weird thing is my code worked for a second and displayed the information properly but as soon as I refreshed the page (I did not touch the code) I got the error which is confusing me the most.
Database Helper class
getFactTitle(String target, int position) async {
Database db = await this.database;
String searchString =
('SELECT title FROM factTable WHERE fid="' + target + '"');
var result = await db.rawQuery(searchString);
if (result.length > 0) {
titles[position] = result.first.values.first.toString();
} else {
return null;
}
}
Grid View
Widget _buttons() {
return Expanded(
child: GridView.count(
crossAxisCount: 2, //NUMBER OF COLUMNS
children: List.generate(numberOfFacts, (index) {
return Center(
child: new Column(children: <Widget>[
IconButton(
icon: Image.asset('assets/pictures/' +
category +
_stringIndex(index) +
'a.jpg'),
onPressed: () {
print("Clicked: " + category + _stringIndex(index));
}),
Text(
_getTitle(index),
),
]),
);
}),
),
);
}
_getTitle(int index) async {
print(titles[index]);
return titles[index];
}
_getTitles() async {
String theTitle;
_getCategory();
for (int i = 1; i <= numberOfFacts; i++) {
String target = category + (i.toString());
await helper.getFactTitle(target, i);
print(titles[i]);
theTitle = titles[i];
}
return theTitle;
}
Since _getTitle(int index)
is async
you'll have to wait for it to complete.
In this case you can use a FutureBuilder
.
FutureBuilder<String>(
future: _getTitle(index),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data);
}
}
);
you could also handle error and waiting state.
More info: https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html