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

Flutter新手求助:如何在AppBar中用DecoratedBox实现特殊背景

Flutter入门开发者问题:实现指定样式的AppBar搜索栏

我是一名Flutter入门开发者,想要实现类似参考图的AppBar搜索栏样式,尝试用DecoratedBox实现但没成功,以下是我的代码:

appBar: AppBar(
  backgroundColor: Colors.red[700],
  actions: [getAppbarActions()],
),
Widget getAppbarActions() {
  return Expanded(
    child: Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: DecoratedBox(
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: BorderRadius.circular(10)),
            child: Row(
              // mainAxisSize: MainAxisSize.max,
              children: [
                Image(
                  image: AssetImage('images/1.png'),
                  width: 40,
                  alignment: Alignment.centerLeft,
                  // height: 15,
                ),
                Text(
                  'hi',
                  textAlign: TextAlign.end,
                  style: TextStyle(color: Colors.black),
                ),
                // Text('hi'),
                // Text('hi'),
              ],
            ),
          ),
        ),
      ],
    ),
  );
}

参考样式:AppBar背景为深红色,右侧有一个白色圆角搜索栏,内部左侧是图标、右侧是文本。


问题分析与修复方案

你的代码有几个核心问题:

  • Expanded在AppBar的actions里不合适:AppBar的actions是横向组件列表,Expanded会强制占满剩余空间,但AppBar的高度逻辑会导致布局异常。
  • Row没有设置对齐方式:内部图标和文本无法按预期左右分布。
  • 搜索栏内部缺少内边距:图标和文本紧贴边框,显得拥挤。

修复后的完整代码:

appBar: AppBar(
  backgroundColor: Colors.red[700],
  elevation: 0, // 可选:移除阴影,让样式更简洁
  actions: [
    // 控制搜索栏宽度,适配屏幕
    Container(
      width: MediaQuery.of(context).size.width * 0.7,
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: DecoratedBox(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(10),
        ),
        // 给搜索栏内部加内边距
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 12),
          child: Row(
            // 图标左对齐,文本右对齐
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Image.asset(
                'images/1.png',
                width: 40,
                height: 40, // 固定图标高度,避免拉伸变形
              ),
              const Text(
                'hi',
                style: TextStyle(color: Colors.black, fontSize: 16),
              ),
            ],
          ),
        ),
      ),
    ),
    const SizedBox(width: 16), // 右侧留空白,避免搜索栏贴边
  ],
),
关键修改说明
  1. 替换Expanded为Container,通过比例设置搜索栏宽度,适配不同屏幕尺寸。
  2. 在DecoratedBox内部添加Padding,让图标、文本与搜索栏边框保持合理间距。
  3. 设置Row的mainAxisAlignment: MainAxisAlignment.spaceBetween,实现图标左、文本右的布局效果。
  4. 给图标添加固定高度,防止因AppBar高度变化导致图标拉伸。
  5. 在actions末尾添加SizedBox,让搜索栏右侧有留白,提升视觉体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 13:55:29