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

如何让Flutter Autocomplete组件的选项显示在输入框上方?

调整Flutter Autocomplete选项框到输入框上方

要把Autocomplete的建议选项显示在输入框正上方,你可以通过自定义optionsViewBuilder的布局定位实现,核心是借助Positioned组件结合输入框的尺寸信息计算位置。

修改后的完整代码示例

return Autocomplete<String>(
  // 保留原有其他配置
  fieldViewBuilder: (BuildContext context,
            TextEditingController fieldTextEditingController,
            FocusNode focusNode,
            VoidCallback onFieldSubmitted) {
    // 给TextField添加GlobalKey用于获取位置尺寸
    final textFieldKey = GlobalKey();
    return TextField(
      key: textFieldKey,
      controller: fieldTextEditingController,
      focusNode: focusNode,
      onSubmitted: (_) => onFieldSubmitted(),
      // 保留原有其他配置
    );
  },
  optionsViewBuilder: (BuildContext context,
            AutocompleteOnSelected<String> onSelected,
            Iterable<String> options) {
    // 获取输入框的渲染对象,计算位置和尺寸
    final textFieldRenderBox = context.findRenderObject() as RenderBox;
    final textFieldSize = textFieldRenderBox.size;
    final textFieldOffset = textFieldRenderBox.localToGlobal(Offset.zero);

    return Positioned(
      // 定位到输入框正上方,bottom值为输入框高度+间距
      bottom: textFieldSize.height + 8,
      left: textFieldOffset.dx,
      width: textFieldSize.width,
      child: Material(
        elevation: 4.0,
        child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            color: Colors.white,
          ),
          child: ListView.builder(
            padding: EdgeInsets.zero,
            shrinkWrap: true, // 必须设置,避免列表高度溢出
            itemCount: options.length,
            itemBuilder: (context, index) {
              final option = options.elementAt(index);
              return ListTile(
                title: Text(option),
                onTap: () => onSelected(option),
              );
            },
          ),
        ),
      ),
    );
  },
);

关键改动说明

  • 给TextField添加GlobalKey,用于获取它的渲染对象,从而得到输入框的位置和尺寸数据。
  • 使用Positioned组件固定选项框位置,通过bottom属性将其定位在输入框正上方,数值可根据需求调整间距。
  • 给ListView.builder设置shrinkWrap: true,确保列表仅占用实际所需高度,避免布局溢出问题。

额外提示

如果页面包含滚动组件(如ListView),建议将Autocomplete嵌套在Stack组件内,这样Positioned的定位不会受滚动影响,显示更稳定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 16:43:09