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

如何在Flutter中实现从ListView页面向表单页面传递数据

解决方案:ListView条目数据传递到表单页面

步骤1:修改ListPage的点击事件与数据返回逻辑

当前代码中_sendDataBack方法返回的是未使用的输入框内容,需改为传递点击条目的对应数据:

  1. 调整GestureDetector的onTap,将当前点击的suggestion传入方法:
GestureDetector(
  onTap: () {
    _sendDataBack(context, suggestion); // 传入当前选中的条目数据
  },
  // 其余代码保持不变
)
  1. 修改_sendDataBack方法,返回选中条目的名称(若需要ID或完整对象,可按需调整):
void _sendDataBack(BuildContext context, SearchSuggestion suggestion) {
  Navigator.pop(context, suggestion.name);
}

步骤2:修正NextPage的页面跳转与数据接收逻辑

当前代码跳转的页面不对,需改为你的列表页面ListPage,并将返回的数据更新到表单输入框:

  1. 修改_awaitReturnValueFromSecondScreen中的跳转目标页面:
final result = await Navigator.push(
  context,
  MaterialPageRoute(
    builder: (context) => ListPage(), // 改为ListPage
  ),
);
  1. 将返回的数据赋值给输入框控制器,更新表单显示:
setState(() {
  if (result != null) {
    _controller.text = result; // 把选中的名称填入输入框
  }
});

完整修改后的关键代码片段

ListPage中showSearchSuggestions方法修改后:

Widget showSearchSuggestions() {
  List suggestionlist = List.from(data["data"].map((i) {
    return SearchSuggestion.fromJSON(i);
  }));
  return Column(
    children: suggestionlist.map((suggestion) {
      return InkResponse(
        child: GestureDetector(
          onTap: () {
            _sendDataBack(context, suggestion);
          },
          child: SizedBox(
            width: double.infinity,
            child: Card(
              child: Container(
                decoration: BoxDecoration(color: Styles.background),
                padding: EdgeInsets.all(15),
                child: Text(
                  suggestion.name,
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
          ),
        ),
      );
    }).toList(),
  );
}

void _sendDataBack(BuildContext context, SearchSuggestion suggestion) {
  Navigator.pop(context, suggestion.name);
}

NextPage中_awaitReturnValueFromSecondScreen方法修改后:

void _awaitReturnValueFromSecondScreen(BuildContext context) async {
  final result = await Navigator.push(
    context,
    MaterialPageRoute(
      builder: (context) => ListPage(),
    ),
  );

  setState(() {
    if (result != null) {
      _controller.text = result;
    }
  });
}

补充说明

如果需要传递完整的条目数据(包含ID和名称),可以直接返回suggestion对象:

// ListPage中返回完整对象
Navigator.pop(context, suggestion);

// NextPage中接收并处理
final SearchSuggestion? result = await Navigator.push(...);
setState(() {
  if (result != null) {
    _controller.text = result.name;
    // 如需使用ID,可通过result.id获取
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 04:30:57