Flutter Firebase - Not able to fetch data from Firestore

Viewed 36

I am trying to get the data from "savedGoal" collection and somehow it is throwing error (NoSuchMethodError). However same script/syntax of code is working absolutely fine for another collection on same firebase project. Please let me know what could be wrong here. Here is the script that I am running in ininState()-

FirebaseFirestore.instance
        .collection("savedGoals")
        .where('uid', isEqualTo: FirebaseAuth.instance.currentUser.uid)
        .get()
        .then((value) {
      value.docs.forEach((result) async {
        if (result.data().isNotEmpty) {
          setState(() {
            goalAmount = result.data()['goalAmountFixed'];
          });
        }

Here is the screenshot of error that I am receiving while using "savedGoal" collection - enter image description here

Here is the firebase document screenshot- enter image description here

2 Answers

Check main.dart to ensure that you have initialized Firebase correctly. In case you have not initialized Firebase in your project then try initializing it by adding this in main:

main() async {
    await Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform,
    );
}

If that's not the case then can you please send add the logs related to this issue. Also cross check the format of the code. Use results.isNotEmpty() instead of results().data.isNotEmpity().

You don't need to call .data() to get the value of the key. just get the value of your key directly from QuerySnapshot as I did below.

FirebaseFirestore.instance
    .collection("savedGoals")
    .where('uid', isEqualTo: FirebaseAuth.instance.currentUser!.uid)
    .get()
    .then((value) {
  for (var result in value.docs) {
    if (result.data().isNotEmpty) {
      setState(() {
        goalAmount = result['goalAmountFixed'];
      });
    }
  }
});

Mark this answer as correct if it helped and solved your issue or if you are still having issues then please comment on this answer I will help.

Edit: Let us know if you still need help.

Related