为什么从其他文件访问时 Flutter GlobalKey 的 currentState 为 NULL

Why Flutter GlobalKey's currentState is NULL when accessed from other file

这是我的代码:

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 时:

所以看起来 GlobalKey.currentState 只有当涉及此 GlobalKey 的所有内容都在同一个文件中时才有效。

文档仅声明当 (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.currentState 将为 null 它没有声明所有内容都必须在同一个文件中。

将 classes 分解成文件可能不是 "the Dart way",但我认为它应该无论如何都可以工作(它们都是 public)。所以这让我很困惑,我怀疑我是否偶然发现了我不知道的某些 Flutter 功能。谢谢。

这是由于飞镖导入的工作原理。

在 dart 中,有两种导入源的方法:

  • 导入'./relative/path.dart'
  • 进口[=52​​=]

问题是,它们彼此不兼容。这两个导入将具有不同的 runtimeType.

但这怎么会是个问题呢?我从未使用过相对导入

这是一个问题,因为在某些情况下你隐式使用 "relative imports" :当使用 class A 定义在 foo.dart inside foo.dart.

那么,我该如何解决这个问题呢?

有多种解决方案:

  • 与您的 class App 相关的所有内容都应该在同一个文件中。 (这是dart中推荐的东西)
  • App 提取到它自己的文件中。并使用绝对导入将其导入任何地方。
  • 不要使用 GlobalKey 作为开头。因为你的用例肯定在InheritedWidget的范围内。