Flutter:类型'Future<dynamic>'不是类型'Widget'的子类型

10

我正在使用sqlite在我的Flutter应用程序中存储数据。我有一个modal底部工作表,其中包含筛选芯片,当您选择一个芯片时,它会将该项添加到数据库中。如果该项已经存在,则筛选芯片被选中。当我调用数据库函数以检查该项是否已经存在时,我收到如下错误。

我已尝试使用异步和等待。

数据库查询代码:

// 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,
        );
}


2个回答

16

您的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());
       }
      ),
    ],

1
我已经寻找这个东西一个小时了。非常感谢! - Shankar Thiyagaraajan

1
有时候会出现这样的情况,错误地给函数分配了async功能,但在函数块内部没有使用await进程。
类似的情况已经发生在我身上,通过删除未使用的async来解决上述问题。
当您使任何函数成为async时,函数请求者会以Future<T>的方式处理它,因此要小心。

我的StreamBuilder需要Stream<QuerySnapshot<Object?>>类型的数据,但它返回的是Future类型的数据,并在控制台中出现错误“type 'Future<dynamic>' is not a subtype of type 'Stream<QuerySnapshot<Object?>>?'”,请建议如何修复。谢谢。 - Kamlesh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接