我正在使用sqlite在我的Flutter App中存储数据。我有一个模态底部打开过滤片,当你选择一个时,它会将项目添加到数据库中。如果该项目已存在,则检查过滤器芯片。当我调用数据库函数来检查项目是否已经存在时,我得到以下错误。
我尝试过使用async和await。
数据库查询代码:
// FIND TAG
findTag(int tagId) async {
var dbConnection = await db;
var res = await dbConnection.query("$TABLE_NAME", where: "tagId = ?", whereArgs: [tagId]);
return res.isNotEmpty ? true : false ;
}
模态底部小部件容器代码:
Widget build(BuildContext context) {
setState(() {
_index = widget.index;
_list =widget.list;
});
return new Container(
padding: new EdgeInsets.all(27.0),
child: new Column(
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget> [
new Text(_list[_index]["title"], style: new TextStyle( fontWeight: FontWeight.bold, fontSize: 22),),
new Text(_list[_index]["description"]),
getFilterChipsWidgets(),
],
),
);
}
getFilterChipsWidgets()
async {
List<Widget> tagsList = new List<Widget>();
for(var i=0; i<_list[_index]["tags"].length; i++) {
var dbHelper = DBHelper();
int id = int.parse(_list[_index]["tags"][i]["id"]);
var exist = await dbHelper.findTag(id);
FilterChip item = new FilterChip(
label: Text(_list[_index]["tags"][i]["name"].toString(),),
selected: exist,
onSelected: (bool newValue) {
if(newValue) {
dbHelper.addNewTag(id);
} else {
dbHelper.deleteNewTag(id);
}
},
);
tagsList.add(item);
}
return Wrap(
spacing: 8.0, // gap between adjacent chips
runSpacing: 4.0, // gap between lines
children: tagsList,
);
}
你的getFilterChipsWidgets()是异步函数,所以它将返回Future。你可以等待将来并保存小部件列表并在完成后调用setState。或者像FutureBuilder一样包装它:
children: <Widget> [
new Text(_list[_index]["title"], style: new TextStyle(fontWeight: FontWeight.bold, fontSize: 22),),
new Text(_list[_index]["description"]),
FutureBuilder<Widget>(
future: getFilterChipsWidgets,
builder: (BuildContext context, AsyncSnapshot<Widget> snapshot){
if(snapshot.hasData)
return snapshot.data;
return Container(child: CircularProgressIndicator());
}
),
],