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

Flutter如何通过路由在两个页面之间传递数组数据?

问题解答

1、当前Navigator.push传递数组的写法是否正确?

你的传参逻辑本身没有语法问题,但有两处需要调整才能正常拿到预期数据:

  • 你当前把onTap回调里的getItems()注释掉了,点击跳转时不会触发遍历选中项存入holder_1的逻辑,最终传递给第二个页面的会是空数组,需要先把这行的注释取消。
  • 不要用List作为自定义变量名,List是Dart内置的数组类型关键字,容易触发编译异常,建议替换为gameSelectStatus这类自定义名称。

2、第二个页面如何接收传递的数组数据

你只需要给目标页面BallGamesSelectedItems增加接收参数的构造函数即可,示例代码如下:

// 假设BallGamesSelectedItems是StatefulWidget,写法如下
class BallGamesSelectedItems extends StatefulWidget {
  // 定义接收数组的参数,明确指定List<String>类型更严谨
  final List<String> selectedGames;
  // 构造函数,接收传入的数组
  const BallGamesSelectedItems(this.selectedGames, {super.key});

  @override
  State<BallGamesSelectedItems> createState() => _BallGamesSelectedItemsState();
}

class _BallGamesSelectedItemsState extends State<BallGamesSelectedItems> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("选中项目")),
      body: ListView.builder(
        //  State类中通过widget.selectedGames即可访问传入的数组
        itemCount: widget.selectedGames.length,
        itemBuilder: (context, index) => ListTile(
          title: Text(widget.selectedGames[index]),
        ),
      ),
    );
  }
}

如果BallGamesSelectedItems是StatelessWidget,写法更简单,直接在build方法中访问定义好的selectedGames参数即可。


补充优化建议

建议修改getItems方法,每次执行前先清空holder_1,避免用户多次修改选中状态时,旧数据被累加进数组:

getItems() {
  holder_1.clear();
  // 这里的List替换为你修改后的自定义变量名
  List.forEach((key, value) {
    if (value == true) {
      holder_1.add(key);
    }
  });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 20:45:01