Martin Seubert
Martin Seubert

Reputation: 1028

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

I am trying to build an app with different lists of games. As a backend I use Firebase and the connection is working fine, I tested it. Anyway I have problems with replacing the mock data with real data from firebase. I always get this error:

type 'Future < dynamic>' is not a subtype of type 'List < Game>'

I have following function:

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);

});
}

"Game" looks like that:

factory Game.fromDocument(DocumentSnapshot document) {

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

);
}

In my build widget I call "getGames":

new HorizontalGameController(getGames()),

Any idea why this error occures and how to solve that?

EDIT:

For better understanding here is my 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]);
      }),
);
}
}

Upvotes: 0

Views: 2175

Answers (1)

nonybrighto
nonybrighto

Reputation: 9593

getGames is not returning the gameList you created. Make the function return the list of games. I can't test it, but give this a try

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 

EDIT Change new HorizontalGameController(await getGames()) to the code below (wrap it with a futureBuilder). This will enable the widget make use of the future value.

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

Upvotes: 1

Related Questions