I’m using Flutter with the Provider plugin and I occurred in a error I cannot help myself out.
Inside my main.dart I have this “container”
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
MyWiget(),
Consumer<LoaderProvider>(
builder: (context, loader, child) {
return Positioned.fill(
child: loader.isLoading ? const OverlayLoadingView() : const SizedBox(),
);
},
),
Consumer<NotificationProvider>(
builder: (context, notification, child) {
if (notification.message.isNotEmpty) {
WidgetsBinding.instance.addPostFrameCallback((_) {
ScaffoldMessenger.of(context)
.showSnackBar(
SnackBar(content: Text(notification.message)),
)
.closed
.then(
(_) => notification.remove(),
);
});
}
return const SizedBox();
},
),
],
),
);
}
and mywidget is:
class MyWidget extends StatelessWidget {
const MyWidget({super.key});
@override
Widget build(BuildContext context) {
return Consumer3<HttpProvider, LoaderProvider, NotificationProvider>(
builder: (context, http, loader, notification, child) {
return FutureBuilder(
future: http.get('...'),
builder: (context, snapshot) {
loader.show();
if (snapshot.hasError) {
notification.addException(snapshot.error!);
}
return Container();
},
);
},
);
}
}
The error I receive, every time the code hit loader.show()
or notification.addException(snapshot.error!)
is
══╡ EXCEPTION CAUGHT BY FOUNDATION LIBRARY ╞═════════════════════
The following assertion was thrown while dispatching
notifications for LoaderProvider:
setState() or markNeedsBuild() called during build.
This _InheritedProviderScope<LoaderProvider?> 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<LoaderProvider?>
The widget which was currently being built when the offending
call was made was:
FutureBuilder<MyClass>
Now, I can understand the error, but how to resolve it? Shouldn’t the LoaderProvider and NotificationProvider be “isolated” inside the consumer, so the MyWidget should not render every time?
I’m using Flutter 3.19.6 and Dart 3.3.4