簡體   English   中英

Flutter:輸入“ Future” <dynamic> &#39;不是&#39;Widget&#39;類型的子類型

[英]Flutter: type 'Future<dynamic>' is not a subtype of type 'Widget'

我正在使用sqlite在Flutter應用程序中存儲數據。 我有一個模態底片,該底片用過濾器芯片打開,當您選擇一個時,會將其添加到數據庫中。 如果該項目已經存在,則檢查濾片。 當我調用數據庫函數檢查該項目是否已經存在時,出現以下錯誤。

我已經嘗試使用異步和等待。

數據庫查詢代碼:

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

有時還可以看到,錯誤地為您分配了async函數,並且在功能塊內部沒有分配您正在使用await進程的位置,

我已經發生過類似的情況,通過刪除該函數上未使用的async ,可以解決上述問題。

當您使任何函數async ,函數請求者都將以Future<T>方式進行處理,因此請當心。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM