簡體   English   中英

Flutter錯誤:輸入&#39;Future <dynamic> &#39;不是&#39;List類型的子類型 <Game> “

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

我正在嘗試使用不同的游戲列表構建一個應用程序。 作為后端,我使用Firebase,並且連接正常,我對其進行了測試。 無論如何,我在用Firebase的真實數據替換模擬數據時遇到問題。 我總是收到此錯誤:

類型“未來<動態>”不是類型“列表<游戲>”的子類型

我有以下功能:

getGames() async{
 List newGamesList = [];

  QuerySnapshot result = awaitFirestore.instance.collection('products').getDocuments();
  List<DocumentSnapshot> documents = result.documents;
  documents.forEach((DocumentSnapshot doc) {
  Game game = new Game.fromDocument(doc);
  newGamesList.add(game);

});
}

“游戲”如下所示:

factory Game.fromDocument(DocumentSnapshot document) {

return new Game(
  name: document['name'],
  box: document['box'],
  cover: document['cover'],
  description: document['description'],

);
}

在我的構建小部件中,我將其稱為“ getGames”:

new HorizontalGameController(getGames()),

知道為什么會發生此錯誤以及如何解決該錯誤嗎?

編輯:

為了更好地理解,這里是我的Horizo​​ntalGameController:

class HorizontalGameController extends StatelessWidget {
HorizontalGameController(this.gameItems);
final List<Game> gameItems;

@override
Widget build(BuildContext context) {
return new SizedBox.fromSize(
  size: const Size.fromHeight(240.0),
  child: new ListView.builder(
      itemCount: 1,
      scrollDirection: Axis.horizontal,
      padding: const EdgeInsets.only(left: 12.0, top: 4.0),
      itemBuilder: (BuildContext context, int position) {
        return GameContainerItem(context, gameItems[position]);
      }),
);
}
}

getGames不返回您創建的gameList。 使函數返回游戲列表。 我無法測試,但可以嘗試一下

Future<List<Game>> getGames() async{
 List<Game> newGamesList = [];

  QuerySnapshot result = await Firestore.instance.collection('products').getDocuments();
  List<DocumentSnapshot> documents = result.documents;
  documents.forEach((DocumentSnapshot doc) {
  Game game = new Game.fromDocument(doc);
  newGamesList.add(game);

});

return newGamesList;
}

//then this
//new HorizontalGameController(await getGames()) //change this 

編輯將 new HorizontalGameController(await getGames())更改為以下代碼(將它與futureBuilder包裝在一起)。 這將使小部件能夠利用未來的價值。

FutureBuilder<List<Game>>(
                            future: getGames(),
                            builder: (context, AsyncSnapshot<List<Game>> gamelistSnapshot){
                                  return (gamelistSnapshot.hasData)? HorizontalGameController(gamelistSnapshot.data) : Container();
                            },
                        )

暫無
暫無

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

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