Jay Tillu
Jay Tillu

Reputation: 1548

How to access data of a filter query in firestore flutter?

I want to search for the user from his mobile number. If the user found then show his other information like Name, Surname.

enter image description here

The search query is working fine. But I'm not able to access the data. Below is my function to get the result of the query. When I print the data its just prints [Instance of 'QueryDocumentSnapshot']

  getData() async {
    final QuerySnapshot result = await FirebaseFirestore.instance
        .collection('CommonData')
        .where(
          'Mobile_Number',
          isEqualTo: mobileNumber,
        )
        .get();
    final List<DocumentSnapshot> resultDocument = result.docs;
    
    print(resultDocument);
  }

Upvotes: 0

Views: 1250

Answers (2)

Thierry
Thierry

Reputation: 8383

Since you make the assumption that your DB does contain one and only one User per Mobile Number, you might want to enforce this assumption:

Future<Map<String, dynamic>> getData(String mobileNumber) async {
  return FirebaseFirestore.instance
      .collection('CommonData')
      .where(
        'Mobile_Number',
        isEqualTo: mobileNumber,
      )
      .get()
      .then((snapshot) => snapshot.docs.single.data())
      .catchError(
    (e) {
      if (e.message == 'No element') {
        print("Couldn't find User for Mobile Number $mobileNumber");
      } else if (e.message == 'Too many elements') {
        print("Found duplicate Users for Mobile Number $mobileNumber");
      }
      return null;
    },
    test: (e) => e is StateError,
  );
}

Upvotes: 1

Raine Dale Holgado
Raine Dale Holgado

Reputation: 3460

Try this

getData() async {
  String mobile_number;
  String name;
  String surname;

  final QuerySnapshot result = await FirebaseFirestore.instance
      .collection('CommonData')
      .where(
        'Mobile_Number',
        isEqualTo: mobileNumber,
      )
      .get();
  result.docs.forEach((value) {
    mobile_number = value.data()['Mobile_Number'];
    name = value.data()['Name'];
    surname = value.data()['SurName'];
  });

  print("Mobile Number: " + mobile_number);
  print("Name: " + mobile_number);
  print("SurName: " + mobile_number);
}

Upvotes: 1

Related Questions