dart Flutter无法传递可选路由参数

oxf4rvwz  于 9个月前  发布在  Flutter
关注(0)|答案(1)|浏览(108)

我试图在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
     }
   }

字符串

k4ymrczo

k4ymrczo1#

尝试访问settings.arguments之前,请先检查ModalRoute.of(context)是否为null。类似于以下内容:

@override
  Widget build(BuildContext context) {
    final route = ModalRoute.of(context);
    
    if (route != null) {
      final args = route.settings.arguments;
      if (args != null) {
        editObject = args;
        edited = true;
      }
    }

字符串
或者,你甚至可以使用?来代替!

final routeArgs = ModalRoute.of(context)?.settings.arguments;

相关问题