NoSuchMethodError:使用 await 和 async 方法在 null 上调用了方法“ancestorStateOfType”

Lou*_*eck 7 android navigator dart flutter

我想创建一个加载器数据,在数据加载结束时屏幕将自动更改屏幕(使用导航器)。

但我有一些问题。

Unhandled Exception: NoSuchMethodError: The method 'ancestorStateOfType' was called on null.
Run Code Online (Sandbox Code Playgroud)

在“getDataOfUser()”方法结束时,“print(a)”执行得很好,但是当它尝试更改屏幕时它崩溃了,我有这个错误:

E/flutter (32148): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method 'ancestorStateOfType' was called on null.
E/flutter (32148): Receiver: null
E/flutter (32148): Tried calling: ancestorStateOfType(Instance of 'TypeMatcher<NavigatorState>')
E/flutter (32148): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:50:5)
E/flutter (32148): #1      Navigator.of (package:flutter/src/widgets/navigator.dart:1446:19)
E/flutter (32148): #2      LoginScreenPresenter.initState.<anonymous closure> (package:test_app/login_presenter.dart:35:17)
Run Code Online (Sandbox Code Playgroud)
Unhandled Exception: NoSuchMethodError: The method 'ancestorStateOfType' was called on null.
Run Code Online (Sandbox Code Playgroud)

Blo*_*oss 6

我遇到了这个问题,我检查了一下mounted,现在它工作正常。

{...
  if(!mounted) return;
  Navigator.of(context).pop();
...}
Run Code Online (Sandbox Code Playgroud)


Mic*_*ono 5

context从来没有被分配过。您正在使用该上下文调用 Navigator,而它仍然为空。尝试在构建时使用页面中的上下文为其分配。

@override
Widget build(context) {
  setState(() => this.context = context);
  ...
}
Run Code Online (Sandbox Code Playgroud)

  • 'context' 是一个最终变量,只能设置一次。尝试使“上下文”成为非最终的。 (3认同)