flutter - 颤动中的“多个小部件使用相同的 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
但错误仍然出现。
切换页面时出现错误。有谁能帮助我吗?
解决方案
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
先前注册的相同类型。
推荐阅读
- python - 如何将高音扬声器数据保存在 json 文件中?
- c# - 如何添加带参数值且不带 lambda 表达式的委托
- javascript - for 循环遍历 index[0] 两次
- python - 我需要创建一个 pandas 数据框,显示推文所代表的主题
- r - 将 data.frame 对象中的数值变量添加到包含 multpolygons 的 sf 对象
- spring - 使用 mongoDb(如 Firebase 或 Realtime Server 应用程序)的 Spring Boot
- javascript - 为什么我的反应应用程序中的后续警报会显示给定会话中显示的第一个警报中的“useCountdown 挂钩计时器”?
- php - 如何在 Wordpress 中使用新的 wp_query 实例
- reactjs - 如何使用 React hook 在 React Native 中使用 TextInput 更改对象数组的特定字符串?
- javascript - 如何从 Vue 组件调用 Rest API?