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

Flutter中如何将ListViewBuilder内列表的选中TextField数据传递到其他页面

实现方案

步骤1:定义数据结构存储列表项状态

首先需要统一管理所有TextField的输入值和选中状态,避免ListView懒加载导致的数据丢失,可先定义通用的表单项类:

class FormItem {
  final String id;
  String inputValue;
  bool isSelected;
  FormItem({required this.id, this.inputValue = '', this.isSelected = false});
}

在当前页面的State中初始化表单列表:

// 示例生成10个表单项,可根据实际业务替换为你的数据源
List<FormItem> formItems = List.generate(10, (index) => FormItem(id: index.toString()));

步骤2:在ListView.builder中绑定状态和TextField

通过onChanged实时同步TextField的输入值到列表,同时绑定选中逻辑(示例用Checkbox做选中触发,也可替换为行点击等交互):

ListView.builder(
  itemCount: formItems.length,
  itemBuilder: (context, index) {
    final currentItem = formItems[index];
    return Row(
      children: [
        Checkbox(
          value: currentItem.isSelected,
          onChanged: (val) {
            setState(() {
              formItems[index].isSelected = val ?? false;
            });
          },
        ),
        Expanded(
          child: TextField(
            onChanged: (inputVal) {
              // 实时更新存储的输入值
              formItems[index].inputValue = inputVal;
            },
            decoration: InputDecoration(hintText: '请输入第${index+1}项内容'),
          ),
        )
      ],
    );
  }
)

步骤3:跳转页面前提取选中数据并传递

触发跳转时先过滤出所有选中的项,通过路由的arguments参数传递到目标页:

ElevatedButton(
  onPressed: () {
    // 过滤选中项,按需整理传递的数据结构
    final selectedData = formItems
        .where((item) => item.isSelected)
        .map((item) => {'id': item.id, 'inputValue': item.inputValue})
        .toList();
    // 跳转并传值
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const TargetPage(),
        settings: RouteSettings(arguments: selectedData),
      ),
    );
  },
  child: const Text('提交并跳转'),
)

步骤4:目标页接收传递的数据

在目标页通过ModalRoute获取传入的参数:

class TargetPage extends StatelessWidget {
  const TargetPage({super.key});

  @override
  Widget build(BuildContext context) {
    // 接收参数,可根据实际数据类型调整强转规则
    final List<Map<String, dynamic>> selectedData = 
        ModalRoute.of(context)?.settings.arguments as List<Map<String, dynamic>>;
    return Scaffold(
      appBar: AppBar(title: const Text('接收数据页')),
      body: ListView.builder(
        itemCount: selectedData.length,
        itemBuilder: (context, index) {
          return Padding(
            padding: const EdgeInsets.all(16),
            child: Text('选中项${selectedData[index]['id']}的输入值:${selectedData[index]['inputValue']}'),
          );
        },
      ),
    );
  }
}

补充注意事项

  • 如果表单项数量较多,不建议为每个TextField单独创建TextEditingController,使用onChanged同步值的方案内存占用更低
  • 若使用Provider、GetX等状态管理库,也可将选中数据存在全局状态中,目标页直接读取全局状态即可,无需走路由传参
  • 选中交互可按需调整,比如点击TextField所在行就标记选中,只需给行外层加GestureDetector更新isSelected状态即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 07:24:04