Flutter 组件之 AppBar、TabBar、TabBarView

1、AppBar 自定义顶部按钮图标、颜色

AppBar AppBar({
  Key? key,
  Widget? leading,    //在标题前面显示的一个控件
  bool automaticallyImplyLeading = true, //当 leading 为 null 时是否隐藏 leading 控件,默认 true
  Widget? title,    //标题
  List<Widget>? actions,    //底部控件。通常用tabBar来表示放置Tab标签栏;
  Widget? flexibleSpace,  //此小部件堆叠在工具栏和选项卡栏的后面。它的高度与应用栏的整体高度相同
  PreferredSizeWidget? bottom,    //通常放tabBar,标题下面显示一个 Tab 导航栏
  double? elevation,  //应用栏阴影大小
  double? scrolledUnderElevation,    // 如果要在内容滚动到 AppBar 下时保持标高,只需将它设置为非零值
  bool Function(ScrollNotification) notificationPredicate = defaultScrollNotificationPredicate,  // 检查组件是否需要监听下拉事件
  Color? shadowColor,    //应用栏阴影颜色
  Color? surfaceTintColor,    //用于应用程序栏背景色的表面色调覆盖的颜色
  ShapeBorder? shape,     //描边形状,可使用其子类构建标题栏形状
  Color? backgroundColor,    //导航背景颜色
  Color? foregroundColor,    //导航栏中文本和图标的颜色
  IconThemeData? iconTheme,    //图标样式
  IconThemeData? actionsIconTheme,  //title 右侧小部件图标颜色,大小,阴影
  bool primary = true,     //true时,appBar 会以系统状态栏高度为间距显示在下方;false 时,会和状态栏重叠。
  bool? centerTitle,    //标题是否居中显示
  bool excludeHeaderSemantics = false,    //标题是否应该用  Semantics 包裹,默认false
  double? titleSpacing,    //title 在水平轴上的间距
  double toolbarOpacity = 1.0,    //应用栏透明度
  double bottomOpacity = 1.0,    //应用栏底部 bottom 的透明度
  double? toolbarHeight,    //应用栏高度
  double? leadingWidth,    //左侧 leading 的宽度,默认56
  TextStyle? toolbarTextStyle,    //导航栏图标的颜色
  TextStyle? titleTextStyle,    //导航栏标题的默认颜色
  SystemUiOverlayStyle? systemOverlayStyle,    //叠加层样式
  bool forceMaterialTransparency = false,    //是否强制 Material 透明,默认 false
  Clip? clipBehavior,    //裁剪样式
})

使用示例

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: const Center(
          child: Text("测试测试测试"),
        ),
        appBar: AppBar(
          title: const Text("data"),
          backgroundColor: Colors.green,
          leading: const Icon(Icons.abc),
          // automaticallyImplyLeading: false,
          actions: [
            IconButton(
                onPressed: () {
                  print("search click");
                },
                icon: const Icon(Icons.search)),
            IconButton.filled(
                onPressed: () {
                  print("more click");
                },
                icon: const Icon(Icons.more_horiz))
          ],
          flexibleSpace: const Text(
            "Hello 我在这里呢!!!",
            style: TextStyle(color: Colors.red),
          ),
          foregroundColor: Colors.yellow,
        ),
      ),
    );
  }
}

2、Tabbar 属性介绍

TabBar TabBar({
  Key? key,
  required List<Widget> tabs,    // tab组件集合,一般使用Tab对象,也可以是其他的Widget
  TabController? controller,    //TabController对象
  bool isScrollable = false,    //是否可滚动
  EdgeInsetsGeometry? padding,    //设置选中Tab指示器间距,默认值为 EdgeInsets.zero
  Color? indicatorColor,    //指示器颜色
  bool automaticIndicatorColorAdjustment = true,    //是否自动调整indicatorColor
  double indicatorWeight = 2.0,    //指示器高度
  EdgeInsetsGeometry indicatorPadding = EdgeInsets.zero,  //底部指示器的Padding
  Decoration? indicator,    //指示器decoration,例如边框等
  TabBarIndicatorSize? indicatorSize,  //指示器大小,TabBarIndicatorSize.label 跟文字等宽,TabBarIndicatorSize.tab 跟每个tab等宽
  Color? dividerColor,   // 分隔符颜色
  Color? labelColor,      //选中label颜色
  TextStyle? labelStyle,    //选中label的Style
  EdgeInsetsGeometry? labelPadding,    //每个label的padding值
  Color? unselectedLabelColor,    //未选中label颜色
  TextStyle? unselectedLabelStyle,    //未选中label的Style
  DragStartBehavior dragStartBehavior = DragStartBehavior.start,    //处理拖动开始行为的方式
  MaterialStateProperty<Color?>? overlayColor,    //定义响应焦点、悬停和飞溅颜色
  MouseCursor? mouseCursor,    //鼠标指针进入或悬停在鼠标指针上时的光标
  bool? enableFeedback,    //检测到的手势是否应提供声音和/或触觉反馈
  void Function(int)? onTap,    //单击Tab时的回调
  ScrollPhysics? physics,    //TabBar的滚动视图如何响应用户输入
  InteractiveInkFeatureFactory? splashFactory, // 水波纹效果
  BorderRadius? splashBorderRadius,  // 水波纹Radius
})

3、TabBarView 属性介绍

TabBarView TabBarView({
  Key? key,
  //子页面,注意保持 TabBarView.children 数量、DefaultTabController.length, TabBar.tabs 三者数量相同。
  required List<Widget> children,  
  // TabController 控制页面切换与 TabBar 设置相同的 TabController达到联动效果
  TabController? controller,   
  //滑动效果,如滑动到末端时,继续拉动,使用 ClampingScrollPhysics 实现 Android 下微光效果。使用 BouncingScrollPhysics 实现 iOS 下弹性效果。
  ScrollPhysics? physics,  
  //启动时阻尼效果,默认为 DragStartBehavior.start
  DragStartBehavior dragStartBehavior = DragStartBehavior.start,
  //为每个 Page 页占据整个 PageView 比例;
  double viewportFraction = 1.0,
  //裁剪样式
  Clip clipBehavior = Clip.hardEdge,
})

4、Tabbar 和 TabBarView 使用

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

//1 混入 SingleTickerProviderStateMixin
class _HomePageState extends State<HomePage>
    with SingleTickerProviderStateMixin {
//数据
  final int _numbs = 20;
  final List<Widget> _titleList = [];
  final List<Widget> _contentList = [];

//2 初始化
  late TabController _tabController;
  @override
  void initState() {
    super.initState();

    //数据初始化
    for (var i = 0; i < _numbs; i++) {
      _titleList.add(Text("第 $i 页"));
      _contentList.add(Text("第 $i 页的内容"));
    }

    _tabController = TabController(
        length: _numbs,
        vsync:
            this); //注: 此处的 length 长度既要与下面 bottom 中的 tabs 数量一致,又要和 body 中 children 的数量一致.
    _tabController.addListener(() {
      if (_tabController.animation?.value == _tabController.index) {
        print("当前选中的索引值为: ${_tabController.index}"); //获取点击或滑动页面的索引值
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
          //PreferredSize 可以改变 appBar 的高度
          preferredSize: const Size.fromHeight(50),
          child: AppBar(
            title: const Text("TabBar"),
            backgroundColor: Colors.red,

            //3 注: tabs 数量既要与上面 TabController 中的 length 长度一致,又要和下面 body 中 children 的数量一致.
            bottom: TabBar(
                isScrollable: true, //是否可滚动
                padding:
                    const EdgeInsets.all(5), //设置选中Tab指示器间距,默认值为 EdgeInsets.zero
                indicatorColor: Colors.green, //指示器颜色
                automaticIndicatorColorAdjustment: true, //是否自动调整indicatorColor
                indicatorWeight: 4, //指示器高度
                indicatorPadding: const EdgeInsets.all(0), //底部指示器的Padding
                indicatorSize: TabBarIndicatorSize.label, //指示器大小
                labelColor: Colors.white, //选中label颜色
                labelStyle: const TextStyle(
                  //选中label的Style
                  fontSize: 15,
                ),
                unselectedLabelColor: Colors.grey, //未选中label颜色
                unselectedLabelStyle: const TextStyle(
                    //未选中label的Style
                    fontSize: 12),
                controller: _tabController,
                tabs: _titleList),
          )),
      //注: children 中的数量既要与上面 TabController 中的 length 长度一致,又要和上面 bottom 中的 tabs 数量一致.
      body: TabBarView(
          controller: _tabController,
          // physics: const ClampingScrollPhysics(), //滑动效果
          // dragStartBehavior: DragStartBehavior.down,//启动时阻尼效果
          // viewportFraction: 0.5,  //为每个 Page 页占据整个 PageView 比例
          // clipBehavior: Clip.none, //裁剪样式
          children: _contentList),
    );
  }
}

补充

1、 preferredSize 组件

PreferredSize 可以改变 appBar 的高度

Scaffold(
    appBar: PreferredSize( 
       preferredSize: Size.fromHeight(50), 
       child: AppBar( 
             .... 
       ) ),
    body: Test(...),
 )
2、监听 TabController 改变事件
 void initState() { 
     super.initState(); 
     _tabController = TabController(length: 8, vsync: this); //监听_tabController的改变事件
     _tabController.addListener(() { 
         if (_tabController.animation!.value==_tabController.index){ 
               print(_tabController.index); //获取点击或滑动页面的索引值 }
         }
     ); 
}
3、MaterialApp 去掉 debug 图标
return MaterialApp( 
     debugShowCheckedModeBanner:false , //去掉debug图标 
     home:Tabs(),
     ... 
);
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 229,565评论 6 539
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 99,115评论 3 423
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 177,577评论 0 382
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 63,514评论 1 316
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 72,234评论 6 410
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 55,621评论 1 326
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 43,641评论 3 444
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 42,822评论 0 289
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 49,380评论 1 335
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 41,128评论 3 356
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 43,319评论 1 371
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 38,879评论 5 362
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 44,548评论 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 34,970评论 0 28
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 36,229评论 1 291
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 52,048评论 3 397
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 48,285评论 2 376

推荐阅读更多精彩内容