【发布时间】:2018-08-26 21:34:06
【问题描述】:
这是我的代码:
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应该重建,并且原色会在蓝色和红色之间切换。
事实上,在我尝试将代码的各个部分拆分为不同的文件之前,代码一直有效。第 (X) 行的 App.appStateKey.currentState 将在以下情况下变为 null:
- A 部分(
App类或变量)被移动到另一个文件; - C 部分(
MyHomePage和_MyHomePageState)被移动到另一个文件; - A 部分和 C 部分已移至另一个文件
所以看起来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 功能。谢谢。
【问题讨论】:
-
涉及的文件有哪些,如何导入?
-
例如,当我将
App类移动到另一个名为types.dart的文件中时,该文件将在main.dart中使用以下语句导入:import 'package:testapp/types.dart';