You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中ModalRoute取arguments转int每次返回null问题求解

问题原因
  • 你将获取路由参数的代码写在了MyApp组件的build方法中,ModalRoute.of(context)需要基于包含MaterialApp的上下文才能获取到路由实例,而MyApp是MaterialApp的父组件,对应上下文尚未挂载路由相关能力,因此返回null。
  • 你通过Navigator.pushNamed传递的arguments: 60是绑定在/ogrenciListesi路由上的,只有进入对应路由页面后,在目标页面的上下文中才能获取到该参数,根组件MyApp无法获取其他路由的参数。
修复方案
  1. 删除MyApp类build方法中获取参数的冗余代码:
// 需删除的代码
int elemanSayisi = ModalRoute.of(context)!.settings.arguments as int;
print('Eleman Sayısı Alındı : $elemanSayisi');
  1. 在目标页面OgrenciListesi的build方法中编写参数获取逻辑:
class OgrenciListesi extends StatelessWidget {
  const OgrenciListesi({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 在此处获取对应路由的参数
    int elemanSayisi = ModalRoute.of(context)!.settings.arguments as int;
    print('Eleman Sayısı Alındı : $elemanSayisi');
    return Scaffold(
      // 你的页面业务代码
    );
  }
}
可选优化

为避免参数为空导致的类型强转崩溃,可以增加判空与缺省值处理:

int? elemanSayisi = ModalRoute.of(context)?.settings.arguments as int?;
int finalSayi = elemanSayisi ?? 0; // 为空时默认赋值0

内容的提问来源于stack exchange,提问作者mehmettalhairmak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 00:09:03