FilledStacks / flutter-tutorials

The repo contains the source code for all the tutorials on the FilledStacks Youtube channel.
MIT License
4.75k stars 1.76k forks source link

Provider Implementation Build issues #64

Closed CathalButler closed 4 years ago

CathalButler commented 4 years ago

Hi,

I am following your Provider Implementation found here but I have run into some issues.

I have created a widget like this one from your example:

class Comments extends StatelessWidget {
  final int postId;
  Comments(this.postId);

  @override
  Widget build(BuildContext context) {
    return BaseView<CommentsModel>(
        onModelReady: (model) => model.fetchComments(postId),
        builder: (context, model, child) => model.state == ViewState.Busy
            ? Center(child: CircularProgressIndicator())
            : Expanded(child: ListView(
                children: model.comments
                    .map((comment) => CommentItem(comment))
                    .toList(),
              )));
  }
}

It works as intended with one widget but when I create another widget just like it but instead it uses another function from the model class ie. ` onModelReady: (model) => model.anotherFunction(), I am getting

The following assertion was thrown while dispatching notifications for CommentsModel setState() or markNeedsBuild() called during build. This _DefaultInheritedProviderScope<CommentsModel> widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building.

Do I need to make another model class to handle that event or should the architecture design support multiple widgets use the same models to call different functions in that model or is this causing me to run into build issues as multi widgets states are being updated at the same time?

Thanks.

FilledStacks commented 4 years ago

Usually a view to viewmodel binding is one to one. But one viewmodel can be used with multiple views. It all depends on what you're calling in that initialise function. If it's a navigation or showing a dialog or anything that will cause a rebuild it will throw that error.

You'll have to call it after the current frame is rendered.

CathalButler commented 4 years ago

Ok, thank you. The issue was with using dialogs.

I have gone with the one to one for view models. Thanks for you great tutorials they are a massive help working with Flutter!