Flutter实现:大屏幕下让可滚动底部导航栏居中
解决底部导航栏大屏居中+小屏滚动问题
核心问题是原代码中Expanded强制让ListView占满剩余宽度,导致大屏下按钮组被拉伸,无法居中。通过以下调整实现需求:
- 用
Flexible替代Expanded,避免强制占满宽度 - 用
IntrinsicWidth让ListView宽度等于所有子按钮的总宽度 - 用
Center包裹ListView,实现空间充足时的居中效果 - 设置
ListView.shrinkWrap: true,让ListView适配内容宽度
修改后的完整代码:
bottomNavigationBar: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( onPressed: null, child: Icon(Icons.cancel_outlined), ), SizedBox(width: 8), // 添加间距优化布局 Flexible( child: SizedBox( height: 30, child: Center( child: IntrinsicWidth( child: ListView( scrollDirection: Axis.horizontal, shrinkWrap: true, children: [ ElevatedButton( onPressed: () => setState(() { filterLanguage[1]; }), style: ElevatedButton.styleFrom(backgroundColor: Colors.grey), child: const Text("Real Life"), ), SizedBox(width: 4), ElevatedButton( onPressed: () => setState(() {}), style: ElevatedButton.styleFrom(backgroundColor: Colors.lightBlue), child: const Text("Python"), ), SizedBox(width: 4), ElevatedButton( onPressed: () => setState(() {}), style: ElevatedButton.styleFrom(backgroundColor: Colors.orange), child: const Text("HTML"), ), SizedBox(width: 4), ElevatedButton( onPressed: () => setState(() {}), style: ElevatedButton.styleFrom(backgroundColor: Colors.red), child: const Text("Java"), ), SizedBox(width: 4), ElevatedButton( onPressed: () => setState(() {}), style: ElevatedButton.styleFrom(backgroundColor: Colors.blue[600]), child: const Text("Flutter"), ), SizedBox(width: 4), ElevatedButton( onPressed: () => setState(() {}), style: ElevatedButton.styleFrom(backgroundColor: Colors.purple), child: const Text("C++"), ), SizedBox(width: 4), ElevatedButton( onPressed: () => setState(() {}), style: ElevatedButton.styleFrom(backgroundColor: Colors.teal), child: const Text("Arduino"), ), SizedBox(width: 4), ElevatedButton( onPressed: () => setState(() {}), style: ElevatedButton.styleFrom(backgroundColor: Colors.green[900]), child: const Text("Kotlin"), ), SizedBox(width: 4), ElevatedButton( onPressed: () => setState(() {}), style: ElevatedButton.styleFrom(backgroundColor: Colors.green), child: const Text("My Website"), ), SizedBox(width: 4), ElevatedButton( onPressed: () => setState(() {}), style: ElevatedButton.styleFrom(backgroundColor: Colors.black), child: const Text( "Other", style: TextStyle(color: Colors.white), ), ), ], ), ), ), ), ) ], ),
效果说明
- 大屏场景:按钮组总宽度小于可用空间时,
IntrinsicWidth让ListView宽度等于按钮总宽度,Center使其居中显示 - 小屏场景:按钮组总宽度超过可用空间时,
Flexible让ListView占满剩余宽度,ListView自动允许横向滚动
内容的提问来源于stack exchange,提问作者Sem
相关产品推荐
相关产品推荐

