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

Flutter路由传参报错:需2个位置参数却传入0个的解决办法

问题解决方法

错误根源

你碰到的"2 positional arguments expected, but 0 found"错误,核心原因是DetailsPage的构造函数要求传入两个位置参数,但在路由配置里实例化DetailsPage()时没传值。而且你已经通过Navigator.pushNamed的arguments传递了Note对象,构造函数里的text和listDescription参数完全多余,属于重复设置。

另外还有个隐藏问题:DetailsPage的build方法里嵌套了MaterialApp,这会和根MyApp的MaterialApp冲突,导致导航行为异常(比如返回按钮可能失效)。


具体修复步骤

1. 简化DetailsPage的构造函数

移除构造函数里多余的位置参数,只保留key:

class DetailsPage extends StatefulWidget {
  static const String routeName = "/details";

  const DetailsPage({super.key}); // 移除text和listDescription参数

  @override
  State<DetailsPage> createState() => _DetailsPageState();
}

2. 修正路由配置

现在路由里实例化DetailsPage不需要传参数,原写法即可(错误会自动消除):

routes: {
  DetailsPage.routeName: (ctx) => DetailsPage(),
},

3. 移除DetailsPage里的嵌套MaterialApp

把build方法里的外层MaterialApp去掉,直接返回Scaffold:

@override
Widget build(BuildContext context) {
  // 保留titleSection、buttonSection、textSection的定义...

  return Scaffold( // 直接返回Scaffold,去掉外层MaterialApp
    appBar: AppBar(
      leading: IconButton(
        icon: const Icon(Icons.arrow_back),
        onPressed: () {
          Navigator.pop(context);
        },
      ),
      title: Text(params.title),
    ),
    body: ListView(
      children: [
        Image.asset(
          'lib/images/placeholder.jpg',
          width: 600,
          height: 240,
          fit: BoxFit.cover,
        ),
        titleSection,
        buttonSection,
        textSection,
      ],
    ),
  );
}

效果验证

修改完成后,点击列表项跳转时,Note对象会通过arguments正常传递到详情页,didChangeDependencies里获取的params能正确拿到title和description,页面会正常显示内容,同时路由配置的错误也会消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 04:10:12