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

Flutter TypeAhead组件清空TextField内容后无法获取建议项问题排查

Flutter TypeAhead 无匹配后无法恢复建议项?问题出在这!

问题根源

你写的getSuggestions方法里用了retainWhere,这个方法是直接修改原始的countries列表的!举个例子:当你输入一个完全无匹配的字符时,retainWhere会把列表里所有元素都删掉,此时原countries列表就空了。之后哪怕你删除输入框里的字符,再调用这个方法时,原列表已经没东西了,自然返回空数组。

修复方案

别碰原始列表!每次查询都基于原始列表做过滤,返回一个新的列表就行。把retainWhere换成where——这个方法不会修改原列表,只会返回符合条件的元素迭代器,转成列表就ok了。

修改后的代码:

static List<CustomCountry> getSuggestions(String query) {
  final lowerCaseQuery = query.toLowerCase();
  return countries.where(
    (country) => country.name.toLowerCase().contains(lowerCaseQuery)
  ).toList();
}

额外小优化

  1. 提前把查询字符串转成小写,避免重复调用toLowerCase(),能省点性能~
  2. 把原始countries列表改成不可变的,防止以后不小心修改它:
static final List<CustomCountry> countries = List.unmodifiable([
  const CustomCountry(
    name: "Afghanistan",
    flagUrl: "https://restcountries.eu/data/afg.svg"),
  const CustomCountry(
    name: "Åland Islands",
    flagUrl: "https://restcountries.eu/data/ala.svg"),
  ...
]);

这样如果有人(包括未来的你)不小心写了修改原列表的代码,会直接抛出错误,更容易排查问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 15:03:12