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

Flutter如何实现点击搜索图标后将其移入TextField leading位置

实现方案

核心调整逻辑围绕isSearching状态控制两个位置的显隐:

  • 对AppBar的leading组件做状态判断:仅非搜索状态下展示外部的搜索图标按钮,搜索状态下隐藏该区域
  • 搜索状态下渲染TextField时,在InputDecoration中新增prefixIcon属性,将搜索图标作为输入框前置图标展示
  • 可选配置:给输入框内的搜索图标添加点击退出搜索的交互,符合常规使用习惯
修改后完整代码
// 请确保你已在当前State类中提前定义以下变量:
// bool isSearching = false;
// final Icon customIcon = Icon(Icons.search); // 替换为你自己的自定义图标配置

return Scaffold(
  appBar: AppBar(
    backgroundColor: it_tool_main_grey_accent,
    elevation: 0,
    title: !isSearching
        ? const Text('All')
        : TextField(
            decoration: InputDecoration(
              enabledBorder: const OutlineInputBorder(
                borderSide: BorderSide(color: Colors.black, width: 1.0),
              ),
              hintText: "Search",
              // 输入框前置搜索图标
              prefixIcon: Padding(
                padding: const EdgeInsets.all(4),
                // 保持和原外部图标一致的圆形白色背景样式
                child: DecoratedBox(
                  decoration: const BoxDecoration(shape: BoxShape.circle, color: Colors.white),
                  child: IconButton(
                    icon: customIcon,
                    onPressed: () {
                      // 点击图标退出搜索状态,不需要该交互可删除onPressed配置
                      setState(() {
                        isSearching = false;
                      });
                    },
                  ),
                ),
              ),
            ),
          ),
    automaticallyImplyLeading: false,
    leadingWidth: 55,
    // 非搜索状态才展示外部搜索图标,搜索状态隐藏
    leading: !isSearching
        ? Padding(
            padding: EdgeInsets.only(left: MediaQuery.of(context).size.width / 30),
            child: DecoratedBox(
              decoration: const BoxDecoration(shape: BoxShape.circle, color: Colors.white),
              child: IconButton(
                icon: customIcon,
                onPressed: () {
                  setState(() {
                    isSearching = !isSearching;
                  });
                },
              ),
            ),
          )
        : const SizedBox.shrink(),
  ),
  body: const Text("hi"),
);

内容的提问来源于stack exchange,提问作者Kutluhan Özbakan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:54:00