Edm*_*Tam 4 state key dart flutter
这是我的代码:
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),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,当FAB被点击时,MaterialApp应该重建,并且原色会在蓝色和红色之间切换。
事实上,代码是有效的,直到我试图将代码的各个部分拆分到不同的文件中。App.appStateKey.currentState在线 (X) 将变为null:
App类或变量)被移动到另一个文件;MyHomePage和_MyHomePageState)被移动到另一个文件;因此,GlobalKey.currentState当涉及此 GlobalKey 的所有内容都在同一个文件中时,这似乎是唯一的工作。
该文档仅声明currentState当(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 导入的工作方式。
在 dart 中,有两种导入源的方式:
问题是,它们彼此不兼容。这两种进口都会有不同的runtimeType。
但这怎么会有问题呢?我从未使用过相对导入
这是一个问题,因为在某些情况下,您会隐式使用“相对导入”:当使用在foo.dart inside 中 定义的类 A 时foo.dart。
那么,我该如何解决这个问题呢?
有多种解决方案:
App应该在同一个文件中。(这是 dart 中推荐的东西)App到它自己的文件中。并使用绝对导入将其导入到任何地方。GlobalKey开始。由于您的用例绝对在InheritedWidget.