Flutter如何实现自定义AppBar?解决actions中按钮占满高度的问题
问题原因
你封装的AppBar中Edit按钮占满整个AppBar高度,主要有两个问题:
- 你给承载Edit文本的Container设置了上下各20的padding,直接拉高了容器高度
- AppBar的actions区域默认没有垂直对齐约束,子组件会默认延展到和AppBar同高
解决方法
你只需要调整actions里的自定义按钮部分,给按钮外层加垂直居中约束,同时修改padding参数即可,修改后的完整代码如下:
AppBar _profileAppbar( context, ) { return AppBar( automaticallyImplyLeading: false, title: Row( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Text( "state.username", style: TextStyle( color: Colors.black, fontSize: 24, fontFamily: 'SukumvitSetBold'), ), ], ), actions: <Widget>[ // 图标按钮套一层Center保证对齐一致 Center( child: IconButton( icon: Icon( (IconData( 0xe908, fontFamily: 'wishlistPost', )), color: HexColor("7225FF"), size: 20, ), iconSize: 30.0, onPressed: () => print('Save post'), ), ), // 给InkWell套Center实现垂直居中 Center( child: InkWell( onTap: () {}, child: Container( // 替换原来的上下20padding,改成上下8、水平16,可根据设计调整 padding: EdgeInsets.symmetric(vertical: 8, horizontal: 16), decoration: BoxDecoration( color: Colors.blue, borderRadius: BorderRadius.circular(18.0), ), child: Text( "Edit", style: TextStyle(color: Colors.white), ), ), ), ), SizedBox( width: 16, // 调整右边距大小,可根据设计修改 ), ], iconTheme: IconThemeData( color: Colors.black, ), centerTitle: true, backgroundColor: Colors.white, elevation: 0.0, ); }
如果需要更精确控制按钮高度,也可以给Container加height: 36(数值可根据设计调整)的固定高度参数,效果和调整padding一致。
内容的提问来源于stack exchange,提问作者imdsk
相关产品推荐
相关产品推荐

