flutter:BottomNavigationBar和TabBar

the difference

BottomNavigationBarr and TabBarare both components used to create navigation bars, but they have some differences.

  1. The location is different: BottomNavigationBarusually at the bottom of the screen, used for the main navigation; and TabBarusually at the top or bottom of the screen, used to switch between different views or pages.

  2. Different styles: BottomNavigationBaris a horizontal navigation bar, usually containing a fixed number of icons and tabs. It provides fixed styling and automatically handles switching between checked and unchecked states.

    TabBarCan be displayed horizontally or vertically and is often used to display multiple tabs. It provides more customization options, such as setting custom label styles, background colors, etc.

  3. Different functions: BottomNavigationBar is usually used to navigate between different main pages, and each icon corresponds to a page. It's relatively simple in function and suitable for primary navigation.

    TabBarUsed to switch between different views or pages, and can TabBarViewbe used with to display the content corresponding to each tab. It is more widely used in applications and is suitable for switching and displaying multiple related pages or functions.

In short, BottomNavigationBarit is suitable for simple main navigation, and T abBaris suitable for more complex page switching and content display.

Example: from qq reading

BottomNavigationBar
insert image description here
TabBar

BottomNavigationBar

BottomNavigationBarIt is the component used to create the bottom navigation bar in Flutter. It is often TabBarViewused with to switch content between different tabs.

BottomNavigationBarThere is an items property where each tab of the navbar can be defined. Each tab can contain an icon and a text label.

class SwitcherContainer extends StatefulWidget {
    
    
  const SwitcherContainer({
    
    Key? key}) : super(key: key);

  
  SwitcherContainerState createState() => SwitcherContainerState();
}

class SwitcherContainerState extends State<SwitcherContainer> {
    
    
  String name = '首页';
  List<String> nameList = ['首页', '书籍', '我的'];
  // 激活项
  int _currentIndex = 0;

  
  Widget build(BuildContext context) {
    
    
    return Scaffold(
      appBar: AppBar(
        title: const Text('导航'),
      ),
      body: Center(
        child: Text(name),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const [
          BottomNavigationBarItem(label: '首页', icon: Icon(Icons.home)),
          BottomNavigationBarItem(label: '书籍', icon: Icon(Icons.book)),
          BottomNavigationBarItem(label: '我的', icon: Icon(Icons.perm_identity)),
        ],
        currentIndex: _currentIndex,
        // 激活颜色
        selectedItemColor: Colors.orange,
        //  点击事件
        onTap: (index) {
    
    
          setState(() {
    
    
            _currentIndex = index;
            name = nameList[index];
          });
        },
      ),
    );
  }
}

insert image description here
If there is no special requirement, you can use the one provided by the system. If you want something different, you can take a look at the following two libraries:

  • curved_navigation_bar
  • google_nav_bar

curved_navigation_bar

An easy to implement curved navigation bar

Official address
https://pub-web.flutter-io.cn/packages/curved_navigation_bar

Install

flutter pub add curved_navigation_bar

easy to use

class SwitcherContainerState extends State<SwitcherContainer> {
    
    
  String name = '首页';
  List<String> nameList = ['首页', '书籍', '我的'];
  // 激活项
  int _currentIndex = 0;

  
  Widget build(BuildContext context) {
    
    
    return Scaffold(
      appBar: AppBar(
        title: const Text('导航'),
      ),
      body: Stack(
        children: [
          Container(
            color: Colors.blueAccent,
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height,
            child: null,
          ),
          Container(
            color: Colors.white,
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height - 150,
            child: Text(name),
          )
        ],
      ),
      bottomNavigationBar: CurvedNavigationBar(
        items: const [
          Icon(Icons.home),
          Icon(Icons.book),
          Icon(Icons.perm_identity)
        ],
        height: 60,
        backgroundColor: Colors.blueAccent,
        //激活项
        index: _currentIndex,
        //  点击事件
        onTap: (index) {
    
    
          setState(() {
    
    
            _currentIndex = index;
            name = nameList[index];
          });
        },
      ),
    );
  }
}

insert image description here
It's best to adjust it like I did above, otherwise it's a bit strange, for example:
insert image description here

bottom_navy_bar

A beautiful and vivid bottom navigation. Navigation bar uses your current theme, but you are free to customize

Official address
https://pub-web.flutter-io.cn/packages/bottom_navy_bar

Install

flutter pub add bottom_navy_bar

easy to use

class SwitcherContainerState extends State<SwitcherContainer> {
    
    
  String name = '首页';
  List<String> nameList = ['首页', '书籍', '我的'];
  // 激活项
  int _currentIndex = 0;

  
  Widget build(BuildContext context) {
    
    
    return Scaffold(
      appBar: AppBar(
        title: const Text('导航'),
      ),
      body: Center(
        child: Text(name),
      ),
      bottomNavigationBar: BottomNavyBar(
          //  当前选中项
          selectedIndex: _currentIndex,
          //  列表
          items: [
            BottomNavyBarItem(
                textAlign: TextAlign.center,
                icon: const Icon(Icons.home),
                title: const Text("首页")),
            BottomNavyBarItem(
                textAlign: TextAlign.center,
                icon: const Icon(Icons.book),
                title: const Text("书架")),
            BottomNavyBarItem(
                textAlign: TextAlign.center,
                icon: const Icon(Icons.perm_identity),
                title: const Text("我的"))
          ],
          //  选中事件
          onItemSelected: (index) => setState(() {
    
    
                _currentIndex = index;
                name = nameList[index];
              })),
    );
  }
}

insert image description here

TabBar

In Flutter, TabBaris a commonly used widget for creating a navigation bar with tabs. It is often TabBarViewused together with to achieve the function of switching content between different tabs.

TabBarConsists of TabBarand TabBarViewtwo key components.

TabBarThe :T abBarwidget defines how the tab looks and interacts. It can contain multiple tabs, each represented by a Tab object. Can be specified by setting controllera property to TabBarViewassociate with TabControllerin order to switch between tabs.

TabBarView: TabBarView``小部件是一个可滚动的容器,用于显示与当前选中选项卡相关联的内容。每个选项卡对应一个子小部件,并且可以通过设置controller 属性来与TabBar` association.

class SwitcherContainer extends StatefulWidget {
    
    
  const SwitcherContainer({
    
    Key? key}) : super(key: key);

  
  SwitcherContainerState createState() => SwitcherContainerState();
}

class SwitcherContainerState extends State<SwitcherContainer>
    with SingleTickerProviderStateMixin {
    
    
  // 控制器
  late TabController tabController;

  
  void initState() {
    
    
    super.initState();
    tabController = TabController(length: 3, vsync: this);
  }

  
  void dispose() {
    
    
    super.dispose();
    //  释放
    tabController.dispose();
  }

  
  Widget build(BuildContext context) {
    
    
    return Scaffold(
      appBar: AppBar(
        title: const Text('TabBar Demo'),
        bottom: TabBar( // 使用TabBar作为AppBar的bottom属性
          controller: tabController, // 关联TabController
          tabs: const [
            Tab(text: 'Tab 1'),
            Tab(text: 'Tab 2'),
            Tab(text: 'Tab 3'),
          ],
        ),
      ),
      body: TabBarView( // 使用TabBarView作为body
        controller: tabController, // 关联TabController
        children: const [
          Center(child: Text('Content of Tab 1')),
          Center(child: Text('Content of Tab 2')),
          Center(child: Text('Content of Tab 3')),
        ],
      ),
    );
  }
}

important point:

  • In Flutter, switching between TabBarand TabBarViewusually requires the use of animation effects. In order to achieve this kind of animation effect, you need to use TickerProviderit, which provides an Tickerobject for generating animation time. Rather, it isSingleTickerProviderStateMixin an implemented TickerProvidermixin class.

insert image description here
or

return Column(
   children: [
     TabBar(
       controller: tabController,
       indicatorColor: Colors.red, // 设置选中选项卡下方的指示器颜色
       labelColor: Colors.blue, // 设置选中选项卡的文本颜色
       unselectedLabelColor: Colors.grey, // 设置未选中选项卡的文本颜色
       tabs: const [
         Tab(
           text: 'Home',
         ),
         Tab(
           text: 'Settings',
         ),
       ],
     ),
     Expanded(
       child: TabBarView(
         controller: tabController,
         children: const [
           Center(
             child: Text("Home"),
           ),
           Center(
             child: Text("Settings"),
           )
         ],
       ),
     ),
   ],
 );

insert image description here
Here is a recommendation: tab_indicator_styler, this library is used to modify the indicator style

Official address
https://pub-web.flutter-io.cn/packages/tab_indicator_styler

Install

flutter pub add tab_indicator_styler

basic use

import 'package:tab_indicator_styler/tab_indicator_styler.dart';
Scaffold(
   appBar: AppBar(
     toolbarHeight: 10,
     bottom: TabBar(
       // 使用TabBar作为AppBar的bottom属性
       controller: tabController, // 关联TabController
       indicatorSize: TabBarIndicatorSize.tab,  // 设置指示器宽度
       // 指示器样式
       indicator: MaterialIndicator(
         height: 5,
         topLeftRadius: 8,
         topRightRadius: 8,
         horizontalPadding: 50,
         tabPosition: TabPosition.bottom,
         color: Colors.white
       ),
       tabs: const [
         Tab(text: 'Tab 1'),
         Tab(text: 'Tab 2'),
         Tab(text: 'Tab 3'),
       ],
     ),
   ),
   body: TabBarView(
     // 使用TabBarView作为body
     controller: tabController, // 关联TabController
     children: const [
       Center(child: Text('Content of Tab 1')),
       Center(child: Text('Content of Tab 2')),
       Center(child: Text('Content of Tab 3')),
     ],
   ),
 );

Note: MaterialIndicatorThe width of the style indicator must be used indicatorSize: TabBarIndicatorSize.tab, which is the default value, otherwise an error will be reported
insert image description here

indicator: DotIndicator(
       radius: 5,
       color: Colors.orange,
       //  圆点距离文字的间距,正数在下面,负数在上面
       distanceFromCenter: 20,
     ),

insert image description here

indicator: RectangularIndicator(
      bottomLeftRadius: 30,
      bottomRightRadius: 30,
      topLeftRadius: 30,
      topRightRadius: 30,
    ),

insert image description here

Guess you like

Origin blog.csdn.net/weixin_41897680/article/details/131921103