Search code examples
databasefluttergoogle-cloud-firestoreclouddocument-database

How to save a single document field in cloud firestore into a local variable in flutter?


I would like to save a single document field into a local variable, but I am not able to do that. Here is my code:

void getPostsData() async{
    List<Widget> listItems = [];
    String _title;
    String _content;
    final QuerySnapshot result = await Firestore.instance.collection('Social_Posts').getDocuments();
    final List<DocumentSnapshot> documents = result.documents;
    documents.forEach((data){
      listItems.add(
          GestureDetector(
            onTap: () async{
              print(data["postTitle"]);
              print(data["postContent"]);
              setState(() {
               data["postTitle"] == _title;
               data["postContent"] == _content;
              });
              print(_title);
            },
       )
    );
      }

Whenever I try to print out "_title" or "_content", I get null. Why is that happening and how do I fix this?


Solution

  • You should probably change

           data["postTitle"] == _title;
           data["postContent"] == _content;
    

    to:

           _title = data["postTitle"];
          _content= data["postContent"];