如何实现Flutter AppBar中操作按钮与TabBar同排布局
实现方案
不需要使用Grid布局,用Row组件就能更简单实现需求,核心思路是不要把TabBar放在flexibleSpace属性中(该属性的组件会铺满整个AppBar区域,自然会覆盖首尾按钮),直接在AppBar的title属性中自定义布局即可:
- 给title赋值为一个Row组件,设置
mainAxisAlignment: MainAxisAlignment.spaceBetween,实现首尾按钮和中间TabBar的水平排列 - 给TabBar套一层
Expanded组件,避免Row布局溢出,同时限制TabBar只占中间剩余空间 - 首尾直接放置你需要的操作按钮组件即可
修改后的完整代码如下:
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData( highlightColor: Colors.transparent, splashColor: Colors.transparent, hoverColor: Colors.transparent, ), title: 'Flutter Demo', home: DefaultTabController( length: 2, child: Scaffold( appBar: AppBar( automaticallyImplyLeading: false, backgroundColor: Colors.white, // 核心:自定义title布局 title: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ // 左侧操作按钮 IconButton( icon: Icon(Icons.menu, color: Colors.black), onPressed: () {}, ), // 中间TabBar,用Expanded限制宽度 Expanded( child: TabBar( indicatorColor: Colors.pink[100], tabs: [ Tab(text: 'Dogs'), Tab(text: 'Cats'), ], labelColor: Colors.black, // 可以调整indicatorWeight和indicatorPadding来修改指示器位置 indicatorWeight: 3, indicatorPadding: EdgeInsets.symmetric(horizontal: 30), ), ), // 右侧操作按钮 IconButton( icon: Icon(Icons.more_horiz, color: Colors.black), onPressed: () {}, ) ], ), ), body: TabBarView( children: [ Center(child: Text('DOGS')), Center(child: Text('CATS')), ], ), ), ), ); } }
补充说明
- 如果你需要调整指示器的位置、宽度,可以修改TabBar的
indicatorWeight、indicatorPadding、indicatorSize属性实现预期效果 - Grid布局也可以实现该效果,但对于单行三元素的排列场景,Row的实现成本更低、渲染性能更好,没有必要使用Grid布局
内容的提问来源于stack exchange,提问作者BigPP
相关产品推荐
相关产品推荐

