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

Flutter技术问询:选中Google Places联动ListView项后填充至TextFormField并关闭ListView

解决Flutter中选中地址填充输入框并关闭列表的问题

嘿,这问题其实很好搞定!你已经拿到了选中的selectedItem,只需要结合TextEditingController和状态管理就能实现需求,我给你一步步拆解:

核心思路

  1. 更新TextFormField内容:你已经给TextFormField绑定了_controller,直接通过控制器设置文本就能同步更新输入框的内容。
  2. 隐藏ListView:用一个布尔状态变量控制列表的显示/隐藏,选中地址后切换状态即可实现"关闭"列表的效果。

修改后的完整代码示例

首先在你的State类里新增一个状态变量,用来控制列表的显示:

class _YourWidgetState extends State<YourWidget> {
  late TextEditingController _controller;
  List<Map<String, dynamic>> _placeList = [];
  String? selectedItem;
  bool _showSuggestions = false; // 控制ListView是否显示

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController();
    // 监听输入变化,触发地址查询并更新列表状态
    _controller.addListener(() {
      if (_controller.text.isNotEmpty) {
        // 这里替换成你调用Google Places API获取_placeList的逻辑
        // 示例:假设你已经拿到了API返回的结果
        // _placeList = await fetchPlaces(_controller.text);
        setState(() {
          _showSuggestions = _placeList.isNotEmpty;
        });
      } else {
        setState(() {
          _placeList.clear();
          _showSuggestions = false;
        });
      }
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        TextFormField(
          controller: _controller,
          decoration: textInputDecoration.copyWith(
            labelText: 'Address or Preferred City'
          ),
        ),
        // 用条件渲染控制ListView的显示/隐藏
        if (_showSuggestions)
          ListView.builder(
            physics: const NeverScrollableScrollPhysics(),
            shrinkWrap: true,
            itemCount: _placeList.length,
            itemBuilder: (context, index) {
              return ListTile(
                title: Text(_placeList[index]["description"]),
                onTap: () {
                  selectedItem = _placeList[index]["description"];
                  // 1. 更新输入框文本
                  _controller.text = selectedItem!;
                  // 2. 隐藏地址列表
                  setState(() {
                    _showSuggestions = false;
                  });
                  // 可选:收起键盘,提升体验
                  FocusScope.of(context).unfocus();
                },
              );
            },
          ),
      ],
    );
  }
}

关键细节说明

  • 控制器同步输入框:_controller.text = selectedItem!会直接让TextFormField显示选中的地址,因为输入框和控制器是双向绑定的,这是最直接的更新方式。
  • 状态刷新UI:setState()会触发Widget重建,把_showSuggestions设为false后,ListView就会从界面上消失,完美实现"关闭"列表的需求。
  • 收起键盘优化:加上FocusScope.of(context).unfocus(),用户选中地址后键盘会自动收起,整体交互体验会更流畅。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 12:37:48