当前位置: 首页 > article >正文

Flutter_学习记录_Tab的简单Demo~真的很简单

1. Tab的简单使用了解

要实现tab(选项卡或者标签视图)需要用到三个组件:

  • TabBar
  • TabBarView
  • TabController

这一块,我也不知道怎么整理了,直接提供代码吧:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

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

  
  Widget build(BuildContext context) {
    return  MaterialApp(
      debugShowCheckedModeBanner: true,
      home: Home(),
      theme: ThemeData(
       appBarTheme: AppBarTheme(
         backgroundColor: Colors.yellow, // 设置导航栏颜色为蓝色
        )
      ),
    );
  }
}

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

  
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 3, 
      child: Scaffold(
        appBar: AppBar(
          leading: IconButton(
            onPressed: () => debugPrint("navigation button is pressed."), 
            icon: Icon(Icons.menu),
            tooltip: "Navigation",
          ),
          actions: [
            IconButton(
              onPressed: () => debugPrint("navigation button is pressed."), 
              icon: Icon(Icons.search),
              tooltip: "search",
            )
          ],
          title: Text("App Demo"),
          elevation: 0.0,
          bottom: TabBar(
            unselectedLabelColor: Colors.black38,
            indicatorColor: Colors.black54,
            indicatorSize: TabBarIndicatorSize.label,
            indicatorWeight: 1.0,
            tabs: [
              Tab(icon: Icon(Icons.local_florist)),
              Tab(icon: Icon(Icons.change_history)),
              Tab(icon: Icon(Icons.directions_bike)),
            ]
          ),
        ),
        body: TabBarView(
          children: [
            Icon(Icons.local_florist, size: 128.0, color: Colors.black12),
            Icon(Icons.change_history, size: 128.0, color: Colors.black12),
            Icon(Icons.directions_bike, size: 128.0, color: Colors.black12),
          ]
        ),
     )
    );
  }
}

效果图如下:
在这里插入图片描述

2. Drawer 侧边栏简单使用

在手势在屏幕进行左滑手势时,可以通过设置drawer属性,来实现侧边栏显示的效果。

侧边栏代码的实现如下(为了避免代码太长,新建一个实现Drawer视图的文件):

import 'package:flutter/material.dart';

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

  
  Widget build(BuildContext context) {
    return Drawer(
      child: ListView(
        padding: EdgeInsets.zero,
        children: [
          // DrawerHeader(
          //   decoration: BoxDecoration(
          //     color: Colors.greenAccent
          //   ),
          //   child: Text("Header".toUpperCase()),
          // ),
          UserAccountsDrawerHeader(
            accountName: Text("zhuzhu", style: TextStyle(fontWeight: FontWeight.bold, color: Colors.black)), 
            accountEmail: Text("zhuzhu@com.net", style: TextStyle(color: Colors.black),),
            currentAccountPicture: CircleAvatar(
              backgroundImage: NetworkImage("https://img1.baidu.com/it/u=1368815763,3761060632&fm=253&fmt=auto&app=138&f=JPEG?w=760&h=434"),
            ),
            decoration: BoxDecoration(
              image: DecorationImage(
                image: NetworkImage("https://i-blog.csdnimg.cn/blog_migrate/41635df939e6dd13c6d5e2af785d358b.jpeg"),
                fit: BoxFit.cover,
                colorFilter: ColorFilter.mode(Colors.yellow.withAlpha(150), BlendMode.srcOver)
              )
            ),
          ),
          ListTile(
            title: Text("Message", textAlign: TextAlign.right),
            trailing: Icon(Icons.message, color: Colors.black12, size: 22.0),
            onTap: () => Navigator.pop(context), // 关闭抽屉
          ),
          ListTile(
            title: Text("Favorite", textAlign: TextAlign.right),
            trailing: Icon(Icons.favorite, color: Colors.black12, size: 22.0),
            onTap: () => Navigator.pop(context), // 关闭抽屉
          ),
          ListTile(
            title: Text("Settings", textAlign: TextAlign.right),
            trailing: Icon(Icons.settings, color: Colors.black12, size: 22.0),
            onTap: () => Navigator.pop(context), // 关闭抽屉
          ),
        ],
      ),
    );
  }
}

然后将DrawerDemo 添加到drawer属性里,代码如下:

import 'package:flutter/material.dart';
import 'Demo/Drawer_demo.dart'; // 导入DrawerDemo所在的文件

void main() {
  runApp(MyApp());
}

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

  
  Widget build(BuildContext context) {
    return  MaterialApp(
      debugShowCheckedModeBanner: true,
      home: Home(),
      theme: ThemeData(
       appBarTheme: AppBarTheme(
         backgroundColor: Colors.yellow, // 设置导航栏颜色为蓝色
        )
      ),
    );
  }
}

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

  
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 3, 
      child: Scaffold(
        appBar: AppBar(
          leading: IconButton(
            onPressed: () => debugPrint("navigation button is pressed."), 
            icon: Icon(Icons.menu),
            tooltip: "Navigation",
          ),
          actions: [
            IconButton(
              onPressed: () => debugPrint("navigation button is pressed."), 
              icon: Icon(Icons.search),
              tooltip: "search",
            )
          ],
          title: Text("App Demo"),
          elevation: 0.0,
          bottom: TabBar(
            unselectedLabelColor: Colors.black38,
            indicatorColor: Colors.black54,
            indicatorSize: TabBarIndicatorSize.label,
            indicatorWeight: 1.0,
            tabs: [
              Tab(icon: Icon(Icons.local_florist)),
              Tab(icon: Icon(Icons.change_history)),
              Tab(icon: Icon(Icons.directions_bike)),
            ]
          ),
        ),
        body: TabBarView(
          children: [
            Icon(Icons.local_florist, size: 128.0, color: Colors.black12),
            Icon(Icons.change_history, size: 128.0, color: Colors.black12),
            Icon(Icons.directions_bike, size: 128.0, color: Colors.black12),
          ]
        ),
        // 添加侧边栏, 用扫动的手势来显示这个侧边栏
        drawer: DrawerDemo()
     )
    );
  }
}

效果如下:
在这里插入图片描述

3. 底部导航栏的添加

底部导航栏的添加,可以通过属性bottomNavigationBar来设置,实现它需要用到这两个组件:

  • BottomNavigationBar
  • BottomNavigationBarItem

之前页面都是静态页面,创建的类也都是继承于StatelessWidget,但是点击tabbar需要根据点击改变状态,所以,就需要用新的组件StatefulWidget。这一次就先只记录怎么使用,后面有时间把这个控件的说明再补充上。

根据前面的代码,抽取出一些代码,并创建以下三个类:

  • ExploreDemo
import 'package:flutter/material.dart';
import 'ListView_demo.dart';
import 'Drawer_demo.dart';


class  ExploreDemo extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 3, 
      child: Scaffold(
        appBar: AppBar(
          leading: IconButton(
            onPressed: () => debugPrint("navigation button is pressed."), 
            icon: Icon(Icons.menu),
            tooltip: "Navigation",
          ),
          actions: [
            IconButton(
              onPressed: () => debugPrint("navigation button is pressed."), 
              icon: Icon(Icons.search),
              tooltip: "search",
            )
          ],
          title: Text("App Demo"),
          elevation: 0.0,
          bottom: TabBar(
            unselectedLabelColor: Colors.black38,
            indicatorColor: Colors.black54,
            indicatorSize: TabBarIndicatorSize.label,
            indicatorWeight: 1.0,
            tabs: [
              Tab(icon: Icon(Icons.local_florist)),
              Tab(icon: Icon(Icons.change_history)),
              Tab(icon: Icon(Icons.directions_bike)),
            ]
          ),
        ),
        body: TabBarView(
          children: [
            ListViewDemo(),
            Icon(Icons.change_history, size: 128.0, color: Colors.black12),
            Icon(Icons.directions_bike, size: 128.0, color: Colors.black12),
          ]
        ),
        // 添加侧边栏, 用扫动的手势来显示这个侧边栏
        drawer: DrawerDemo()
     )
    );
  }
}
  • HistoryDemo
import 'package:flutter/material.dart';

class  HistoryDemo extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("历史记录")),
      body: Container(
        child: Center(
          child: Text("历史记录"),
        ),
      )
    );
  }
}
  • MyviewDemo
import 'package:flutter/material.dart';

class  MyviewDemo extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("个人主页")),
      body: Container(
        child: Center(
          child: Text("个人主页"),
        ),
      )
    );
  }
}

基础工作做好后,在main.dart 文件中,实现如下代码:

import 'package:flutter/material.dart';
import 'Demo/Explore_demo.dart';
import 'Demo/History_demo.dart';
import 'Demo/MyView_demo.dart';

void main() {
  runApp(MyApp());
}

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

  
  Widget build(BuildContext context) {
    return  MaterialApp(
      debugShowCheckedModeBanner: true,
      home: Home(),
      theme: ThemeData(
       appBarTheme: AppBarTheme(
         backgroundColor: Colors.yellow, // 设置导航栏颜色为蓝色
        )
      ),
    );
  }
}

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

  
  State<StatefulWidget> createState() {
    return _HomeState();
  }
}

class _HomeState extends State<Home> {

  int _currentPageIndex = 0;

  // 提前创建3个视图,当点击tabbar的时候,调用setState的index来去对应的页面
  final List<Widget> pageLists = [
    ExploreDemo(),
    HistoryDemo(),
    MyviewDemo()
  ];

  void _onTapHandler (int index) {
    // 更新状态
    setState(() {
      _currentPageIndex = index;
    });
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
        // 根据_currentPageIndex展示视图
        body: pageLists[_currentPageIndex],
        // 设置底部tabbar
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: _currentPageIndex,
          onTap: _onTapHandler,
          type: BottomNavigationBarType.fixed,
          fixedColor: Colors.black,
          items: [
            BottomNavigationBarItem(
              icon: Icon(Icons.explore),
              label: "explore"
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.history),
              label: "history"
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.person),
              label: "My"
            ),
          ]
        )
      );
    }
}

效果图如下:
请添加图片描述


http://www.kler.cn/a/519370.html

相关文章:

  • 【CSS入门学习】Flex布局设置div水平、垂直分布与居中
  • IoTDB 2025 春节值班与祝福
  • 基于ESP32的桌面小屏幕实战[6]:环境搭建和软件基础
  • [Dialog屏幕开发] 屏幕绘制(下拉菜单)
  • 网络知识小科普--5
  • vim如何设置制表符表示的空格数量
  • 【开源免费】基于SpringBoot+Vue.JS智慧图书管理系统(JAVA毕业设计)
  • 【DB】Oracle存储过程
  • doris:MySQL Load
  • 【2025年数学建模美赛E题】(农业生态系统)完整解析+模型代码+论文
  • Vue.js 路由懒加载
  • 【STM32项目实战系列】了解ST系列MCU外设:定时器TIM
  • HTML-新浪新闻-实现标题-排版
  • WPS计算机二级•幻灯片的页面布局
  • 【unity游戏开发之InputSystem——07】InputSystem+UGUI配合使用(基于unity6开发介绍)
  • 【问题解决】el-upload数据上传成功后不显示成功icon
  • C++红黑树详解
  • 参数是模型学会的东西,预训练是让它学习的东西
  • 【C/C++】C++中使用vector存储并遍历数据
  • 【数据结构】_以单链表为例分析各种方法实现的特殊情况考虑思路
  • git基础指令大全
  • 题海拾贝:力扣 232.用栈实现队列
  • 如何在Spring Boot项目中高效集成Spring Security
  • 前端开发中的新兴技术:Web Components 实战应用
  • HTML一般标签和自闭合标签介绍
  • C++解决走迷宫问题:DFS、BFS算法应用