Fix setState() or markNeedsBuild() called during build in Flutter

You might encounter this issue when calling setState() within initState() method of a StatefulWidget.

The following assertion was thrown while dispatching notifications for CommonProvider:
setState() or markNeedsBuild() called during build.

This _InheritedProviderScope<CommonProvider?> 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. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was: _InheritedProviderScope<CommonProvider?>
  value: Instance of 'CommonProvider'
  listening to value
The widget which was currently being built when the offending call was made was: Builder
When the exception was thrown, this was the stack: 

You can fix this issue by wrapping your code within WidgetsBinding.instance!.addPostFrameCallback:

@override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((_) {
      _fetchData();
    });
  }

or SchedulerBinding.instance!.addPostFrameCallback:

@override
  void initState() {
    super.initState();
    SchedulerBinding.instance!.addPostFrameCallback((_) {
      _fetchData();
    });
  }

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close