Home > OS >  Listview updates only after changing screens in flutter
Listview updates only after changing screens in flutter

Time:04-09

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

CodePudding user response:

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

CodePudding user response:

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

  • Related