Home > Back-end >  how to retrive value from a firestore flutter where query
how to retrive value from a firestore flutter where query

Time:04-16

I started flutter recently, and I try to retrieve the data from a query I made using 'where' , but the only thing I got back is "Instance of '_JsonQueryDocumentSnapshot'". I tried different thing , but nothing work or i do it badly this is my code :

CollectionReference users =
      FirebaseFirestore.instance.collection('users');

  final documents =
      await users.where("username", isEqualTo: "username").get();

  documents.docs.forEach((element) {
    print(element);
  });

I have also tried to use Future but without success :

class finduser extends StatelessWidget {
  final String username;

  finduser(this.username);

  @override
  Widget build(BuildContext context) {
    CollectionReference users = FirebaseFirestore.instance.collection('users');

    return FutureBuilder(
      future: users.where('username', isEqualTo: '${username}').get(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.hasError) {
          print("wrong");
          return Text("Something went wrong");
        }

        if (snapshot.hasData && !snapshot.data!.exists) {
          print("doesnt exist");
          return Text("User does not exist");
        }

        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> data = snapshot.data! as Map<String, dynamic>;
          print(snapshot.data!);
          return Text("${data}");
        }

        return Text("loading");
      },
    );
  }
}

for the moment, all usernames are just "username"

firebase

Thank you for the help

CodePudding user response:

I have searched a lot but i see you have written code right.

The only thing that came to my mind is that you didn't initialize your firebase to your flutter project (you should do it in any flutter project to be able to use flutter).

link of the document: https://firebase.flutter.dev/docs/overview#initializing-flutterfire

CodePudding user response:

When you get your documents like this :

CollectionReference users =
          FirebaseFirestore.instance.collection('users');

      final documents =
          await users.where("username", isEqualTo: "username").get();

      documents.docs.forEach((element) {
        print(element);
      });

You are trying to print an instance of a QueryDocumentSnapshot

This QueryDocumentSnapshot has a method .data() which returns a Map<String,dynamic> aka JSON.

So in order to print the content of your Document, do this :

      documents.docs.forEach((element) {
        print(element.data());
      });

This data by itself will not be very useful so I recommend creating a factory method for your class :


class MyClass {
  final String username;

  const MyClass({required this.username});

  factory MyClass.fromJson(Map<String, dynamic> json) =>
      MyClass(username: json['username'] as String);
}

Now you can call MyClass.fromJson(element.data()); and get a new instance of your class this way.

CodePudding user response:

In your first code snippet you are printing element, which are instances of the QueryDocumentSnapshot class. Since you're not accessing specific data of the document snapshot, you get its default toString implementation, which apparently just shows the class name.

A bit more meaningful be to print the document id:

documents.docs.forEach((doc) {
  print(doc.id);
});

Or a field from the document, like the username:

documents.docs.forEach((doc) {
  print(doc.get("username"));
});
  • Related