简体   繁体   中英

how can i read data from firebase (one time read ) using (.get)

how can i get data from document in firebase using the method.get..... i tried this but it didn't work and gived me an empty string. i already tried another method i found on firebase website:

class GetUserName extends StatelessWidget {
  final String documentId;

  GetUserName(this.documentId);

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

    return FutureBuilder<DocumentSnapshot>(
      future: users.doc(documentId).get(),
      builder:
          (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {

        if (snapshot.hasError) {
          return Text("Something went wrong");
        }

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

        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;
          return Text("Full Name: ${data['full_name']} ${data['last_name']}");
        }

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

but it i just need the value to pass it as a parametre like that

      String username = "";
                        users.doc(Uid).get().then((value) {
                          username = value.get('Username').toString();
                        });

any help please?

I checked your code and until last part it looks ok for me.

I think some problem is here:

if (snapshot.connectionState == ConnectionState.done) {
    Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;
    return Text("Full Name: ${data['full_name']} ${data['last_name']}"        
}

First of all - try to print your response:

Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;
print('data: $data');

Then you can see what exactly is coming from your request. If it is empty - maybe you didn't set up your project and\or firebase correctly. Or it can be just wrong variable naming you trying to receive.

But the most fun reason could be just that you have empty database with no data in it. Just try to fill it with needed 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