我试图在Flutter中传递一个对象作为路由参数。为此,我使用ModalRoute.of(context as BuildContext)!.settings.arguments as Object?;
。这个对象应该是可选的。因此我将其设置为空。(对象?)在阅读之后,应该决定它是否存在并相应地采取行动。如果这个对象不存在,我会得到一个错误:Bad state: No element
这不能用try catch拦截。我做错了什么?
late Object? editObject;
bool edited = false;
bool loaded = false;
@override
Widget build(BuildContext context) {
if (!loaded) {
loaded = true;
editRecipe =
ModalRoute
.of(context as BuildContext)!
.settings
.arguments as Object?;
if (editObject != null) {
edited = true;
//filling in the info into the ui
}
}
字符串
1条答案
按热度按时间k4ymrczo1#
在尝试访问
settings.arguments
之前,请先检查ModalRoute.of(context)
是否为null
。类似于以下内容:字符串
或者,你甚至可以使用
?
来代替!
:型