简体   繁体   中英

how to retrive value from a firestore flutter where query

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"

火力基地

Thank you for the help

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(MyClass.fromJson(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.

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

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

Run this code, it will work.

I also faced this similar problem, so I used this work around.

Map<String, dynamic> data = {};

FirebaseFirestore.instance.collection('users').where("username", isEqualTo: "username").get().then((QuerySnapshot querySnapshot) {
    querySnapshot.docs.forEach((value){
            data = value.data()!;
    print('printing uid ${data['uid']}');
    print('printing username--${data['username']}');
    print('printing all data--$data');

   });
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM