'Listview updates only after changing screens in flutter

So, here is my problem.

Logic:

Get the data from firebase. Users can update the data, refresh the listview accordingly.

Problem: Listview DOES update but, only after I change the screen to some other screen and return to the screen with the listview.

Explanantion:

The _postData array is made within the _PostsState.

The data is updated in the array when a user navigates to a new page and comes back with Navigator.pop()

The data is successfully updated and the array size does change but the change in UI is not reflected until screen is changed.

Code:

class Posts extends StatefulWidget {
  const Posts({Key? key}) : super(key: key);

  @override
  _PostsState createState() => _PostsState();
}

class _PostsState extends State<Posts> {
  final DataRepository repository = DataRepository();
  final List<Post> _postData = [];

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

SOME MORE CODE

 SizedBox(
                height: 45.0,
                child: ElevatedButton(
                    style: ButtonStyle(
                        backgroundColor:
                            MaterialStateProperty.all<Color>(Color(0xFF00AC97)),
                        shape:
                            MaterialStateProperty.all<RoundedRectangleBorder>(
                                RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(14.0),
                        ))),
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute<void>(
                            builder: (context) => AddPost()),
                      ).then((_) => {setState(() {})}); <- This doesnot work instantly
                    },
                    child: const Text(
                      'Have anything to share? ',
                      style: TextStyle(
                        fontFamily: 'PoppinsLight',
                        fontWeight: FontWeight.w400,
                        fontSize: 20.0,
                        letterSpacing: 0.3,
                      ),
                    )),
              ),

SOME MORE CODE

      ListView.builder(
        shrinkWrap: true,
        key: UniqueKey(),
        physics: NeverScrollableScrollPhysics(),
        itemCount: _postData.length,
        itemBuilder: (context, index) {
          return Card(
            key: UniqueKey(),
            child: Padding(
              padding: const EdgeInsets.all(14.0),
              child: Column(
                children: [
             
                  Text(_postData[index].postContent.toString(),
                      style: const TextStyle(
                        fontFamily: 'WorkSansLight',
                        fontWeight: FontWeight.w600,
                        fontSize: 15.0,
                        height: 1.75,
                      ))
                ],
              ),
            ),
          );
        },
      )

GETTING NEW DATA

  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);
      });
    });
  }


Solution 1:[1]

You should use FutureBuilder Like This:

    FutureBuilder(
    future: getPosts(),
builder: (context,AsyncSnapshot snapshot){
if(!snapshot.hasData)
return Center(child: CircularProgressIndicator());
else{
  ListView.builder(itemBuilder: itemBuilder)
}
  )

Solution 2:[2]

I figured out the error. Data future is only called within init state. So the UI is not updating.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anas Saradar
Solution 2 crosie