crosie
crosie

Reputation: 45

Listview not updating on Navigator.pop

This event is triggered on a button click. It navigates the user to AddPost() page. When the user comes back with Navigator.pop(), I wish to rebuild the list by fetching new data from the database. However, I am not able to do so.

                     Navigator.push(
                        context,
                        MaterialPageRoute<void>(
                            builder: (context) => AddPost()),
                      ).then((_) => {

                            // setState(() {
                            //   _postData.length;
                            // })

                            super.didChangeDependencies()
                          });

Listview:

        ListView.builder(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        itemCount: _postData.length,
        itemBuilder: (context, index) { ...some things happen })

Function to fetch data from db:

  Future getPosts() async {
    final QuerySnapshot<Map<String, dynamic>> data = await FirebaseFirestore
        .instance
        .collection('posts')
        .orderBy('createdAt', descending: true)
        .get();

    data.docs.forEach((QueryDocumentSnapshot<Map<String, dynamic>> doc) {
      final Post postdata = Post.fromSnapshot(doc);
      setState(() {
        _postData.add(postdata);
      });
    });
  }
}

Init state:

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((_) {
      getPosts();
      print('GET POSTS CALLED');
    });
  }

Upvotes: 0

Views: 294

Answers (1)

Nabin Dhakal
Nabin Dhakal

Reputation: 2202

You can pass the callback function that gets triggered after the sucess message. Try as follows:

    void myFunction(bool value){
if(value){
 getPosts();
}
}

 Navigator.push(
                        context,
                        MaterialPageRoute<void>(
                            builder: (context) => AddPost(myFunction)),
                      ).then((_) => {

                          
                          });

And when you get the success response when adding post call the function:

 if(response.statusCode==200){
    myFunction(true);
    }

Upvotes: 1

Related Questions