我正在尝试构建一个包含不同游戏列表的应用。作为后端,我使用 Firebase 并且连接工作正常,我对其进行了测试。无论如何,我在用来自 firebase 的真实数据替换模拟数据时遇到了问题。我总是收到此错误:
type 'Future < dynamic>' is not a subtype of type 'List < Game>'
我有以下功能:
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]);
}),
);
}
}
最佳答案
getGames 不会返回您创建的游戏列表。使函数返回游戏列表。我无法测试,但请尝试一下
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 包装)。这将使小部件能够使用 future 的值(value)。
FutureBuilder<List<Game>>(
future: getGames(),
builder: (context, AsyncSnapshot<List<Game>> gamelistSnapshot){
return (gamelistSnapshot.hasData)? HorizontalGameController(gamelistSnapshot.data) : Container();
},
)
关于firebase - flutter 错误 : type 'Future<dynamic>' is not a subtype of type 'List<Game>' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55571072/