颤振中“多个小部件使用相同的全局键”错误

时间:2021-03-12 08:11:09

标签: flutter dart

enter image description here

我收到了如图所示的错误。我很困惑,因为我没有在每个页面上都设置 GlobalKey。我刚刚在 GlobalKey 上做了一个 main.dart

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  StreamController<bool> _showLockScreenStream = StreamController();
  StreamSubscription _showLockScreenSubs;
  GlobalKey<NavigatorState> _navigatorKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);

    _showLockScreenSubs = _showLockScreenStream.stream.listen((bool show){
      if (mounted && show) {
        _showLockScreenDialog();
      }
    });
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _showLockScreenSubs?.cancel();
    super.dispose();
  }

  // Listen for when the app enter in background or foreground state.
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      // user returned to our app, we push an event to the stream
      _showLockScreenStream.add(true);
    } else if (state == AppLifecycleState.inactive) {
      // app is inactive
    } else if (state == AppLifecycleState.paused) {
      // user is about quit our app temporally
    } else if (state == AppLifecycleState.suspending) {
      // app suspended (not used in iOS)
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorKey: _navigatorKey,
      ...
    );
  }

  void _showLockScreenDialog() {
    _navigatorKey.currentState.
        .pushReplacement(new MaterialPageRoute(builder: (BuildContext context) {
      return PassCodeScreen();
    }));
  }
}

我已尝试删除 GlobalKey _navigatorKey,但错误仍然出现。

切换页面时出现错误。有谁能帮帮我吗?

1 个答案:

答案 0 :(得分:-1)

Key 有很多种。但是 GlobalKey 允许访问小部件的状态(如果它是 StatefulWigdet)。

然后,如果您对其中的许多使用相同的 GlobalKey,则会与它们的 State 发生冲突。

此外,由于其规格,它们必须属于同一类型:

abstract class GlobalKey<T extends State<StatefulWidget>> extends Key {
  // ...
  void _register(Element element) {
    assert(() {
      if (_registry.containsKey(this)) {
        assert(element.widget != null);
        final Element oldElement = _registry[this]!;
        assert(oldElement.widget != null);
        assert(element.widget.runtimeType != oldElement.widget.runtimeType);
        _debugIllFatedElements.add(oldElement);
      }
      return true;
    }());
    _registry[this] = element;
  }
  // ...
}

这段代码表明,在调试模式下,有一个断言来确保之前没有注册过任何其他相同类型的 GlobalState

相关问题