Home > Software engineering >  How update data from different widgets Flutter
How update data from different widgets Flutter

Time:04-25

I got a list of PostItem with a FutureBuilder.

PostItem got a like button and a like count.

enter image description here

When a click on the post, I go into its details. And I can like the post on this screen.

enter image description here

Here is when I click on the like button in detail screen :

Future<void> _updateLike() async
  {
    PhpPost phpPost = PhpPost();
    phpPost.posteModel = widget.postModel;

    if(_isLike)
    {
      String res = await phpPost.unlikePost();
      if(res=="OK")
      {
        setState(() {
          _isLike = false;
        });
      }
    }
    else
    {
      String res = await phpPost.likePost();
      if(res=="OK")
      {
        setState(() {
          _isLike = true;
        });
      }
    }
    widget.postModel.isLike = _isLike;
  } 

The screen detail update nicely but when I go back at the home screen the post item not updated the like.

Here is how I go to detail from post item :

Navigator.pushNamed(context, '/post_detail', arguments: widget.postModel);

CodePudding user response:

You can use ChangeNotifierProver and when postItem is liked , call notifyListeners().

check this: ChangeNotifierProver

or other methods of state management .

CodePudding user response:

setState here is a local for only this widget and wont rebuild the home page

a simple solution is to try call setState after the await Navigator.pushNamed

which will call setState for the home page after we close the post page

await Navigator.pushNamed(context, '/post_detail', arguments: widget.postModel);
setState((){});

this will work if you are calculate the like count at the build method or you should re-calculate it inside setState


a better solution is to not use a setState at all for handling a user-data change and use state management solution like provider with ChangeNotifier, bloc or riverpod which you will have a controller that will change the data and update the widget

  • Related