我正在尝试使用不同的游戏列表构建一个应用程序。作为后端,我使用Firebase,并且连接正常,我对其进行了测试。无论如何,我在用Firebase的真实数据替换模拟数据时遇到问题。我总是会收到此错误:
“ Future
”类型不是“ List ”类型的子类型
我具有以下功能:
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()),
您知道为什么会发生此错误以及如何解决该错误吗?
编辑:
为了更好地理解,这里是我的HorizontalGameController:
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]);
}),
);
}
}
答案 0 :(得分:1)
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();
},
)