Flutter/Firebase - type 'Future<int>' is not a subtype of type 'int'

吃可爱长大的小学妹 提交于 2021-01-29 19:26:47

问题


I'm new to flutter and this is probably a simple question but i'm looking for a bit of an explanation to help me understand futures and future builder more. I am trying to query firebase (depending on what a user clicks on a previous screen) and i'd like to wait for all the data to be loaded before anything is shown. To do this I thought a future builder would be most appropriate as i'm going to be showing some products that won't change a great deal. I created my getData function:

  Future getCardData() async {
    return await Firestore.instance.collection('cards')
        .where('Event', isEqualTo: widget.documentid).snapshots();
    }
  }

And implemented it here:

  body: FutureBuilder(
    future: getCardData(),
    builder: (context, snapshot) {
      if (!snapshot.hasData) {
        return Center(child: const Text('Loading...'));
      }
      return GridView.builder(
        shrinkWrap: true,
        gridDelegate:
        SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
        itemCount: snapshot.data.length,
        itemBuilder:
            (BuildContext context, int index) {
          print(snapshot.data.documents[index].data['img_url']);
          return Padding(
            padding: const EdgeInsets.all(8.0),
            child: Container(
              height: MediaQuery.of(context).size.height / 6,
              child: Center(
                  child: Card(
                    elevation: 8.0,
                    child: Image(
                      image: FirebaseImage(snapshot.data.documents[index].data['img_url']),
                    ),
                  )
              ),
            ),
          );
        },
      );
    },
  ),

But i'm getting (from what I assume to be the itemCount part of my GridView.buider) an error saying:

type 'Future<int>' is not a subtype of type 'int'

I'm wondering how I can access this future value and then adjust the remainder of my code to wait for the data to load before showing any images.


回答1:


snapshots() returns a Stream, therefore change it to getDocuments():

Future<QuerySnapshot> getCardData() async {
  return await Firestore.instance.collection('cards')
    .where('Event', isEqualTo: widget.documentid).getDocuments();
}

Then in the itemCount you can do the following:

itemCount: snapshot.data.documents.length,


来源:https://stackoverflow.com/questions/63766101/flutter-firebase-type-futureint-is-not-a-subtype-of-type-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!