Search code examples
firebasedartgoogle-cloud-firestorearpnt

how can i get this variable in the "then"?


i take data from firebase , there are datas but i can't access to variable. Can you help me please ? Thank you in advance.

import 'dart:convert';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

class Models {
  var data;
  Map jsondata;

  Future<Map<dynamic,dynamic>> where() async{
    await Firestore.instance
    .collection('musteri')
    .where("name", isEqualTo: "Lion")
    .snapshots()
    .listen((data) =>
        data.documents.map( (DocumentSnapshot document) {
            this.jsondata = document.data;
            print(this.jsondata);
           // There is data here. when i use print(this.jsondata); , data apper in the terminal.
        }).toString(),
      );

      print(this.jsondata); // this is an empty data.

    return jsondata;
  }
}


Solution

  • First thing to note is that when you are running a Firebase Query, the response type you will get is of a QuerySnapshot, which can be easier to understand if you think of them as a List of DocumentSnapshots.

    So you can rephrase your code like this

    QuerySnapshot snapshot = await Firestore.instance
        .collection('musteri')
        .where("name", isEqualTo: "Lion")
        .getDocuments();
    
    

    Now, once you have the query snapshot, you can iterate through it and get the DocumentSnapshot you want.

    snapshot.documents.forEach((document){
      jsondata = document.data;
    });
    

    And then you can return the jsondata. But keep in mind that this jsondata will be the last element in the QuerySnapshot.

    So I think you will also need to rephrase your method to return a List<Map<String, String>> instead of a Map<String, String>

    Overall, your function would look like this

    Future<Map<dynamic, dynamic>> where() async {
    
      QuerySnapshot snapshot = await Firestore.instance
          .collection('musteri')
          .where("name", isEqualTo: "Lion")
          .getDocuments();
    
      snapshot.documents.forEach((document){
        jsondata = document.data;
      });
    
      return jsonData;
    }