Flutter AppBar定义顶部Tab切换(固定)

(一)实现效果及效果图
效果:
(1)这个头部的切换数量是固定的,也就是不可以左右滑动
类似于html里面的选项卡
效果图:
在这里插入图片描述

(二)实现方法
tab组件
tabbarview组件

(三)代码实现
以下是全部代码,如果想要运行,就要在main.dart里面写一个入口函数,在home的位置写AppBarDemoPage()

import 'package:flutter/material.dart';

//不可以左右滑动的头部选项卡效果
class AppBarDemoPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,//选项的个数必须和下面的内容匹配
      child: Scaffold(
        appBar: AppBar(
          title: Text("甜宠软妹"),
          centerTitle: true,
          backgroundColor: Colors.green,
          bottom: TabBar(
            indicatorColor: Colors.red, //指示器
            labelColor: Colors.red,
            unselectedLabelColor: Colors.white,
            indicatorSize: TabBarIndicatorSize.label, //选中的红色条
            tabs: <Widget>[
              Tab(text: "关注"),
              Tab(text: "推荐"),
            ],
          ),
        ),
        body: TabBarView(
          children: <Widget>[
            ListView(
              children: [
                ListTile(
                  title: Text("第一个tab"),
                ),
                ListTile(
                  title: Text("第一个tab"),
                ),
                ListTile(
                  title: Text("第一个tab"),
                )
              ],
            ),
            ListView(
              children: [
                ListTile(
                  title: Text("第二个tab"),
                ),
                ListTile(
                  title: Text("第二个tab"),
                ),
                ListTile(
                  title: Text("第二个tab"),
                ),  
              ],
            )
          ],
        ),
      ),
    );
  }
}

如果多个选项,宽度不够,怎么实现滑动切换呢

猜你喜欢

转载自blog.csdn.net/weixin_45425105/article/details/111690481