skip to Main Content

I am trying to get some fields in my firestore collection/document. I want to display them in some places in my code.

How can i get a particular field, like maybe phoneNumber from the user’s field in the document/collection.

THis is how the user’s data gets stored in the firebase.

//create UsersCollection data (First level verification) == Users Profile

Future createUserData(
    String firstName,
    String lastName,
    String emailAddress,
    String phoneNumber,
    String gender
  ) async{
    return getInstance.collection("users").doc(user!.email)
      .collection("User Profile").doc(uid).set({
        "firstName" : firstName,
        "lastName" : lastName,
        "emailAddress" : emailAddress,
        "phoneNumber" : phoneNumber,
        "gender" : gender
      });
  }

How can I get the phonenUmber maybe. Or even the firstName.

2

Answers


  1. To get data from firebase you can try multiple ways

    For fetching single item

    var collection = FirebaseFirestore.instance.collection('users');
    var docSnapshot = await collection.doc('documentIdhere').get();
    if (docSnapshot.exists) {
      Map<String, dynamic>? data = docSnapshot.data();
      var value = data?['firstName']; // gets the first name
     setState((){});
    }
    

    You can also use a future builder like this

    FutureBuilder<DocumentSnapshot<Map<String, dynamic>>>(
      future: collection.doc('docume tIdHere').get(),
      builder: (_, snapshot) {
        if (snapshot.hasError) return Text ('${snapshot.error}');
    
        if (snapshot.hasData) {
          var data = snapshot.data!.data();
          var firstName = data!['firstName']; 
          return Text('first name is $firstName');
        }
    
        return Center(child: CircularProgressIndicator());
      },
    )
    
    Login or Signup to reply.
  2. you can try this method and store the result in list

    List myListOfValue[];
    
    List myListOfElement[];
    
    
    CollectionReference deliveryList =
    FirebaseFirestore.instance.collection('your Collecetion');
    
    getData() async {
    
          await deliveryList.get().then((value) {
            for (var element in value.docs) {
              // you can get a specific value
              myListOfValue.add(element['your Value in FireStore']);
              // or you can get the entire element and get the value inside the 
               //element later
              myListOfElement.add(element);
           
            }
          });}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search