首页 > 解决方案 > 颤动中的“多个小部件使用相同的 GlobalKey”错误

问题描述

在此处输入图像描述

我收到了一个类似图片中的错误。我很困惑,因为我没有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但错误仍然出现。

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

标签: flutterdart

解决方案


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

然后,如果您GlobalKey对其中许多人使用相同的内容,则与他们State的 s 存在冲突。

此外,由于其规范,它们必须是相同的类型:

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先前注册的相同类型。


推荐阅读