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

Flutter中Navigator.pushNamed无法向目标页面传递参数问题

Flutter Navigator参数传递失败问题修复

问题现象

点击Screen4的ListTile后,参数未成功传递到Screen5,无报错信息,打印语句显示Screen5的title、subtitle始终为空字符串。

错误原因

  1. Screen5中仅获取了ModalRoute.of(context)?.settings?.arguments,但未将其赋值给title和subtitle变量,而是使用了初始化的空字符串。
  2. 未对传递的List类型参数进行解析,Screen4传递的是[title, subtitle]列表,Screen5需要从中提取对应元素。

修复步骤

步骤1:修改Screen5的状态类

移除初始化的空字符串变量,在build方法中解析传递的参数:

class _MyHomePageState extends State<MyHomePage> {
  final _textController = TextEditingController();

  // 移除初始化的空字符串,改为动态获取
  String? title;
  String? subtitle;
  final String? encry= '';


  @override
  Widget build(BuildContext context) {
    // 获取并解析List类型参数
    final args = ModalRoute.of(context)?.settings?.arguments as List<String>?;
    title = args?[0];
    subtitle = args?[1];
    
    print(title);
    print(subtitle);
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Home wifi network:$title, Authentication: $subtitle'),

            TextField(
              controller: _textController,
              decoration: InputDecoration(hintText: "Enter the password of your Wifi network"),
            ),
            TextButton(
              style: TextButton.styleFrom(
                primary: Colors.blue,
              ),
              onPressed: () async {
                String enteredText = _textController.text;
                // 增加非空判断,避免空指针异常
                if(title != null && subtitle != null){
                  final response = await http.get(Uri.parse(
                    "http://10.10.10.254/httpapi.asp?command=wlanConnectApEx:ssid=$title:ch=1:auth=$subtitle:encry=:pwd=$enteredText:chext=1"));
                  if (response.statusCode == 200) {
                    Navigator.pushNamed(context, '/');
                  } else {
                    // 处理请求错误
                  }
                }
              },
              child: Text("Connect"),
            ),
          ],
        ),
      ),
    );
  }
}

步骤2:(可选)优化参数传递方式

为提高可读性,建议传递Map类型参数,Screen4的onTap修改为:

Navigator.of(context).pushNamed(
  '/fifth',
  arguments: {
    'ssid': title,
    'auth': subtitle
  },
);

对应的Screen5解析参数改为:

final args = ModalRoute.of(context)?.settings?.arguments as Map<String, String>?;
title = args?['ssid'];
subtitle = args?['auth'];

额外注意事项

  • 确保路由表中已正确注册/fifth对应的Screen5页面。
  • 始终处理参数为null的情况,避免空指针异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 18:55:27