Raymond Chong
Raymond Chong

Reputation: 79

Flutter - NoSuchMethodError: Class '_MapStream<QuerySnapshotPlatform, QuerySnapshot>' has no instance method 'then'

I wanted to retrieve data from my sub collection. It should return the list of friendid.enter image description here

But I keep getting the NoSuchMethodError snapshot has no instance method then error with the code below. The error is at firebaseMethods.getFriend(Constant.currentId).then((value) line. enter image description here

  Widget friendList() {
    return StreamBuilder(
      stream: friendlistStream,
      builder: (context, snapshot) {
        return snapshot.hasData
            ? ListView.builder(
                itemCount: snapshot.data.docs.length,
                itemBuilder: (context, index) {
                  return FriendTile(
                      snapshot.data.docs[index].data()["friendid"]);
                },
              )
            : Container();
      },
    );
  }

  @override
  void initState() {
    getUserFriend();
    super.initState();
  }

  getUserFriend() async {
    Constant.currentId =
        await HelperFunctions.getUserIdSharedPreference(Constant.currentId);
    setState(() {
      firebaseMethods.getFriend(Constant.currentId).then((value) {
        setState(() {
          friendlistStream = value;
        });
      });
    });
  }

The code for firestore is as below.

getFriend(String ownerid) {
    return FirebaseFirestore.instance
        .collection("users")
        .doc(ownerid)
        .collection("friends")
        .snapshots();
  }

I had tried hardcoding the Constant.currentId to the actual ID that I wanted to retrieve but still having the same error. What should I do to display the list of friendid correctly?

Upvotes: 0

Views: 205

Answers (1)

ahmetakil
ahmetakil

Reputation: 908

Future getFriend(String ownerid) async {
return await FirebaseFirestore.instance
    .collection("users")
    .doc(ownerid)
    .collection("friends")
    .get();

}

.then() is used for futures so your getFriend() method needs to return a Future If you want to use the Stream than you need to use a StreamBuilder instead of calling a function in initState This might help: https://www.youtube.com/watch?v=MkKEWHfy99Y&ab_channel=GoogleDevelopers

Upvotes: 1

Related Questions