Setting provider value in FutureBuilder
Simply remove the notifyListeners();
from the code. I encountered this error and that was what I did to resolve the issue.
I have encountered a problem similar to yours when using the provider. My solution is to add WidgetsBinding.instance.addPostFrameCallback()
when getting the data.
That exception arises because you are synchronously modifying a widget from its descendants.
This is bad, as it could lead to an inconsistent widget tree. Some widget. may be built widgets using the value before mutation, while others may be using the mutated value.
The solution is to remove the inconsistency. Using ChangeNotifierProvider
, there are usually 2 scenarios:
The mutation performed on your
ChangeNotifier
is always done within the same build than the one that created yourChangeNotifier
.In that case, you can just do the call directly from the constructor of your
ChangeNotifier
:class MyNotifier with ChangeNotifier { MyNotifier() { // TODO: start some request } }
The change performed can happen "lazily" (typically after changing page).
In that case, you should wrap your mutation in an
addPostFrameCallback
or aFuture.microtask
:class Example extends StatefulWidget { @override _ExampleState createState() => _ExampleState(); } class _ExampleState extends State<Example> { MyNotifier notifier; @override void didChangeDependencies() { super.didChangeDependencies(); final notifier = Provider.of<MyNotifier>(context); if (this.notifier != notifier) { this.notifier = notifier; Future.microtask(() => notifier.doSomeHttpCall()); } } @override Widget build(BuildContext context) { return Container(); } }