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), // 右侧留空白,避免搜索栏贴边 ], ),
关键修改说明
- 替换
Expanded为Container,通过比例设置搜索栏宽度,适配不同屏幕尺寸。 - 在
DecoratedBox内部添加Padding,让图标、文本与搜索栏边框保持合理间距。 - 设置
Row的mainAxisAlignment: MainAxisAlignment.spaceBetween,实现图标左、文本右的布局效果。 - 给图标添加固定高度,防止因AppBar高度变化导致图标拉伸。
- 在actions末尾添加
SizedBox,让搜索栏右侧有留白,提升视觉体验。
内容的提问来源于stack exchange,提问作者Mr2C2R
相关产品推荐
相关产品推荐

