You need to enable JavaScript to run this app. 如何实现Flutter AppBar中操作按钮与TabBar同排布局
优惠活动
大模型
产品
解决方案
定价
更多

如何实现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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 06:24:04