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

Flutter应用中Autocomplete组件键盘选择功能失效问题

Flutter Autocomplete键盘选择后TextField不更新的修复方案

修复后的代码

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter App!!',
      theme: ThemeData(
        colorSchemeSeed: Colors.indigo,
        useMaterial3: true,
        brightness: Brightness.light,
      ),
      darkTheme: ThemeData(
        colorSchemeSeed: Colors.blue,
        useMaterial3: true,
        brightness: Brightness.dark,
      ),
      home: const MyHomePage(title: 'Flutter Example App'),
      debugShowCheckedModeBanner: false,
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<String> myList = ["Collections", "Records", "Stream API"];
  late TextEditingController textEditingController = TextEditingController(); 

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Autocomplete<String>(
        optionsBuilder: (TextEditingValue textEditingValue){
          if(textEditingValue.text.isEmpty){
            return const Iterable<String>.empty();
          }
          return myList.where((String options){
            return options.toLowerCase().contains(textEditingValue.text.toLowerCase());
          });
        },
        onSelected: (String selection){
          textEditingController.text = selection;
        },
        fieldViewBuilder: (BuildContext context,
            TextEditingController fieldController,
            FocusNode focusNode,
            VoidCallback onFieldSubmitted) {
          return TextField(
            controller: textEditingController,
            focusNode: focusNode,
            onSubmitted: (_) => onFieldSubmitted(),
          );
        },
      )
    );
  }
}

问题原因与说明

  1. 参数重名冲突:原代码中fieldViewBuilder的参数名textEditingController与全局声明的控制器重名,导致全局控制器未被正确关联到TextField,键盘选择时Autocomplete内部逻辑无法触发文本更新。
  2. 冗余代码移除:删除了无意义的textEditingController.text = textEditingController.text代码,避免干扰控制器状态。
  3. 完善回调绑定:在TextField中添加onSubmitted回调,确保按下Enter时能正确触发选项确认逻辑。

如果不需要自定义TextField的样式,可直接去掉fieldViewBuilder,使用Autocomplete默认实现,代码会更简洁:

body: Autocomplete<String>(
  optionsBuilder: (TextEditingValue textEditingValue){
    if(textEditingValue.text.isEmpty){
      return const Iterable<String>.empty();
    }
    return myList.where((String options){
      return options.toLowerCase().contains(textEditingValue.text.toLowerCase());
    });
  },
  onSelected: (String selection){
    textEditingController.text = selection;
  },
)

原问题信息

复现步骤

  • 运行提供的Flutter应用。
  • 聚焦到Autocomplete组件的TextField。
  • 输入内容筛选选项,例如输入"Col"。
  • 使用键盘方向键选中筛选后的选项,例如"Collections"。
  • 按下Enter或Tab键确认选中的高亮选项。

预期结果

TextField应更新为显示选中的选项("Collections")。

实际结果

键盘选择时TextField不更新为选中选项,鼠标选择功能正常。

补充信息

该问题在macOS和Chrome Web应用中均能复现,曾尝试在onSelected回调中显式设置TextEditingController文本,但键盘选择时问题依旧。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 18:04:54