Home > Enterprise >  Flutter, pass object to viewModel trigger recreating of the widget
Flutter, pass object to viewModel trigger recreating of the widget

Time:10-10

I would like to pass a model to a widget and his viewmodel. I use this widget for 2 purposes: Add a new item and Edit the item. So i will pass an empty object in case of new item and an already filled object in case of an edit. Here i create a new post:

                onTap: () {
                  Navigator.pop(context);
                  Navigator.of(context).push(
                    CupertinoPageRoute(
                      builder: (_) => CreatePost(PostPizza()),
                    ),
                  ).then((value) {
                    callback.call();
                  });
                },

Here i set the post in the viewmodel:

class CreatePost extends StatefulWidget {
  final PostPizza post;

  @override
  _CreatePostState createState() => _CreatePostState();

  CreatePost(this.post);
}

class _CreatePostState extends State<CreatePost> {

  @override
  Widget build(BuildContext context) {
    print("Create Post Widget build called");
    PostsViewModel viewModel = Provider.of<PostsViewModel>(context);
    viewModel.setPost(widget.post);

Setting the post object will trigger the text controllers :

    acquaController.text = post.acqua ?? "";
    saleController.text = post.acqua ?? "";
    lievitoTipoController.text = post.lievito?.a ?? "";
    lievitoAmountController.text = post.lievito?.b ?? "";

This will trigger the widget to rebuild continiously.

Any idea how can i solve the issue without all this? This will

CodePudding user response:

You can try this:

class _CreatePostState extends State<CreatePost> {
  bool isSet = false, isLoading = true;
  PostsViewModel? viewModel;
  @override
  Widget build(BuildContext context) {
  print("Create Post Widget build called");
  viewModel = Provider.of<PostsViewModel>(context);
if(isSet == false) {
     isSet = true;
    viewModel.setPost(widget.post);
    isLoading = false;
}
return ....

CodePudding user response:

Try to use this:

viewModel = Provider.of<PostsViewModel>(context, listen: false);

It will not perform rebuild.

Updated Answer, it will be called once:

@override
void initState() {
  viewModel = Provider.of<PostsViewModel>(context, listen: false);
  SchedulerBinding.instance.addPostFrameCallback((_) {
    viewModel.setPost(widget.post);
  });
  super.initState();
}

@override
Widget build(BuildContext context) {
  print("Create Post Widget build called");
  /// Remove this:
  /// PostsViewModel viewModel = Provider.of<PostsViewModel>(context);
  /// viewModel.setPost(widget.post);
  
  /// ...
}
  • Related