我正在尝试使用.of()方法获取我的应用程序的顶级状态,类似于Scaffold.of()函数.这是(精简的)代码:
class IApp extends StatefulWidget {
@override
IAppState createState() => new IAppState();
static IAppState of(BuildContext context) =>
context.ancestorStateOfType(const TypeMatcher<IAppState>());
}
Run Code Online (Sandbox Code Playgroud)
该应用程序使用runApp(新IApp)启动
此窗口小部件创建一个HomePage:
@override
Widget build(BuildContext context) {
return new MaterialApp(
// ommitted: some localization and theming details
home: new HomePage(),
);
}
Run Code Online (Sandbox Code Playgroud)
然后,我尝试从HomePage(StatefulWidget本身)访问状态:
@override
Widget build(BuildContext context) {
return new Scaffold(
// ommited: some Scaffold properties such as AppBar
// runtimeType not actual goal, but just for demonstration purposes
body: new Text(IApp.of(context).runtimeType.toString()),
);
}
Run Code Online (Sandbox Code Playgroud)
奇怪的是,当我将HomePage的代码放在与 IApp 相同的文件中时,代码可以工作,但只是作为一个额外的类.但是,当我将HomePage 放在一个单独的文件 …