I would like guidance on how to avoid this problem that occurs with some users. It’s not a general error.
It seems that flutter disables/dispose the context during my app’s initialization flow.
I’m using FutureBuilder in initState.
The screen only loads after the future method finishes calling several routines.
I initialize my Provider in initiState like this:
` @override void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_userDataController = Provider.of<UserDataController>(context, listen: false);
futureResult = getDataIni();
}`
in my getDataIni method I initialize remote config settings, notifications, etc and call a method from my provider. In some devices it is giving this error when calling the provider method:
await _userDataController.loadData(context);
Error:
Null check operator used on a null value
#0 State.context (package:flutter/src/widgets/framework.dart:954)#1 _HomePageState.getDataIni…..)#2 _FutureBuilderState._subscribe. (package:flutter/src/widgets/async.dart:628)
I know it’s a flutter error and not the provider. But how do I avoid this and guarantee state for the entire application?
My widget is a stateFullWidget.
I expected context to always be available. As I said the error is not general.
3
Answers
But the app cannot keep calling getDataIni() several times. What causes didChangeDependencies to run? getDataIni can only run once on screen opening.
you can use didChangeDependencies lifecycle method instead of initState. In some cases, the context might not be fully initialized or available at the time the initState method is called, so By moving the initialization code to didChangeDependencies, you ensure that the context is available and ready to be used.
In addition to my comments, are you moving the future builder around, or widgets on both sides of it? This would also recreate the state of the
FutureBuilder
and so if yourfutureResult
is not completed yet, then this would also throw an error as soon as it completes.And what is the code of your
_userDataController.loadData(context)
?