Flutter添加Drawer后AppBar标题偏移无法居中对齐怎么解决
问题原因
Flutter中Scaffold添加Drawer组件后,AppBar左侧会自动生成汉堡式抽屉唤起按钮,默认占据leading区域的固定宽度,此时你在title内部套Center仅能在leading右侧的剩余title区域内居中,自然会出现整体向右偏移的现象。
解决方案
方案1:使用AppBar内置居中属性(推荐)
直接给AppBar配置centerTitle: true属性即可,该属性会让标题忽略左右leading、actions的占位,基于整个AppBar的宽度居中,无需额外给Text套Center组件:
Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Chalo"), centerTitle: true, // 新增该行配置 ), drawer: MainDrawer(), body: Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.max, children: [Center(child: Text("You are on a homepage."))], ), ), ); } }
方案2:自定义标题区域占位(特殊场景使用)
如果需要自定义标题的对齐逻辑,也可以给title外层套Container并设置宽度为屏幕宽度减去左右两侧的固定占位宽度,再做居中处理:
AppBar( title: Container( width: MediaQuery.of(context).size.width - 2 * 56, // 左右各预留56dp的按钮占位宽度,可根据实际情况调整 child: Center(child: Text("Chalo")), ), )
内容的提问来源于stack exchange,提问作者Sadam Khan
相关产品推荐
相关产品推荐

