为什么从其他文件访问时Flutter GlobalKey的currentState为NULL
问题内容:
这是我的代码:
import 'package:flutter/material.dart';
void main() {
runApp(new MyStatefulApp(key: App.appStateKey));
}
/// Part [A]. No difference when appStateKey is defined as variable.
class App {
static final GlobalKey<MyAppState> appStateKey = new GlobalKey<MyAppState>();
}
/// Part [B]
class MyStatefulApp extends StatefulWidget {
MyStatefulApp({Key key}) :super(key: key);
@override
MyAppState createState() => new MyAppState();
}
class MyAppState extends State<MyStatefulApp> {
int _counter = 0;
add() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: "App",
theme: new ThemeData(
primarySwatch: _counter % 2 == 0 ? Colors.blue : Colors.red,
),
home: new MyHomePage(),
);
}
}
/// Part [C]
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(title: new Text("Main"), ),
body: new FlutterLogo(),
floatingActionButton: new FloatingActionButton(
onPressed: () {
App.appStateKey.currentState.add(); // (X)
},
tooltip: "Trigger color change",
child: new Icon(Icons.add),
),
);
}
}
在上面的代码中,当单击FAB时,MaterialApp
应进行重建,并且原色将在蓝色和红色之间切换。
实际上,代码一直有效,直到我尝试将代码的各个部分拆分为不同的文件。App.appStateKey.currentState
在以下情况下,(X)行将变为null
:
- A部分(
App
类或变量)被移动到另一个文件; - C部分(
MyHomePage
和_MyHomePageState
)被移到另一个文件; - A部分和C部分移至另一个文件
因此,GlobalKey.currentState
当涉及此GlobalKey的所有内容都在同一文件中时,这似乎是唯一的工作。
该文档仅声明currentState
为null (1) there is no widget in the tree that matches this global key, (2) that widget is not a StatefulWidget, or the associated State object is not a subtype of T.
,而没有声明所有内容必须位于同一文件中。
将类拆分为文件可能不是“
Dart方式”,但我认为它应该以任何方式起作用(它们都是公开的)。因此,这使我感到困惑,并且我怀疑是否偶然发现了我不知道的某些Flutter功能。谢谢。
问题答案:
这是由于飞镖导入的工作原理。
在dart中,有两种导入源的方法:
- 导入’./relative/path.dart’
- 导入’myApp / absolute / path.dart’
问题是,它们彼此不兼容。这两种进口将有不同runtimeType
。
但这是一个问题吗? 我从未使用过相对导入
这是一个问题,因为在某些情况下,您会隐式使用“相对导入”:当使用在foo.dart
inside中 定义的类A时foo.dart
。
那么,我该如何解决问题呢?
有多种解决方案:
- 与类相关的所有内容
App
都应放在同一文件中。(这是飞镖推荐的东西) - 解压
App
到它自己的文件中。并使用绝对导入将其导入到任何地方。 - 不要用
GlobalKey
开始。由于您的用例肯定在的范围内InheritedWidget
。