Nosuchmethoderror: The Method 'ancestorstateoftype' Was Called On Null With Await And Async Method
Solution 1:
I got this issue and I checked mounted
, now it's working fine.
{...
if(!mounted) return;
Navigator.of(context).pop();
...}
Solution 2:
Your context
was never assigned. You are calling Navigator using that context while it is still null. Try to assign it with the context from the page when it is built.
@overrideWidgetbuild(context) {
setState(() =>this.context = context);
...
}
Solution 3:
If you are trying to implement a loading dialog while an action is being performed, be aware that if your dialog does not have time to actually build itself, it will throw this error.
The below example will likely fail because the showLoadingDialog
and its corresponding pop
have no delay between each other, so the context
doesn't have time to exist in the showLoadingDialog
yet:
///DON'T DO THIS
final GlobalKey<State> _loadingKey = GlobalKey<State>();
ListTile(
leading: Text("Sign Out"),
onTap: () async {
showLoadingDialog(context, _loadingKey);
Navigator.of(_loadingKey.currentContext, rootNavigator: true)
.pop();
},
),
However, a delay of allowing the showLoadingDialog
to build should allow the pop
to work without the error showing:
/// This works without error
final GlobalKey<State> _loadingKey = GlobalKey<State>();
ListTile(
leading: Text("Sign Out"),
onTap: () async {
showLoadingDialog(context, _loadingKey);
await Future.delayed(Duration(seconds: 2));
Navigator.of(_loadingKey.currentContext, rootNavigator: true)
.pop();
},
),
I'm not suggesting you add await Future.delayed...
statements in your code to get your dialog to work correctly, but I initially couldn't figure out why some of the showLoadingDialog
s were working and one wasn't -- so hopefully this guides somebody down a faster path to resolution.
Solution 4:
I was using global state variable
final GlobalKey<State> _keyLoader = new GlobalKey<State>();
I was trying to pop the context using below line of code
Navigator.of(_keyLoader.currentContext, rootNavigator: true).pop();
Since my code has many nested loop this code was giving me the error. I instead used below code to fix this error message
Navigator.of(context, rootNavigator: true).pop();
At times it is observed that in the nested loop the context is not correctly set when using global state variable and can lead to this error message.
Post a Comment for "Nosuchmethoderror: The Method 'ancestorstateoftype' Was Called On Null With Await And Async Method"