Flutter之BottomNavigationBar的封裝

圖片描述

BottomNavigationBar
BottomNavigationBar 是屬於 Scaffold 中的一個位於底部的控件。一般和 BottomNavigationBarItem 配合使用。
BottomNavigationBar構造方法:ide

BottomNavigationBar({
        Key key,
        @required this.items,
        this.onTap,
        this.currentIndex = 0,
        this.elevation = 8.0,
        BottomNavigationBarType type,
        Color fixedColor,
        this.backgroundColor,
        this.iconSize = 24.0,
        Color selectedItemColor,
        this.unselectedItemColor,
        this.selectedIconTheme = const IconThemeData(),
        this.unselectedIconTheme = const IconThemeData(),
        this.selectedFontSize = 14.0,
        this.unselectedFontSize = 12.0,
        this.selectedLabelStyle,
        this.unselectedLabelStyle,
        this.showSelectedLabels = true,
        bool showUnselectedLabels,
      })

BottomNavigationBarItem
底部導航欄要顯示的Item,有圖標和標題組成
BottomNavigationBarItem構造方法:ui

const BottomNavigationBarItem({
        @required this.icon,
        this.title,
        Widget activeIcon,
        this.backgroundColor,
      })

構建BottomNavigationBarthis

// 建立底部BottomNavigationBar
      BottomNavigationBar _bottomNavigationBar(List <String>titles, List <String>icons){
        return  BottomNavigationBar(
          items: [
            _bottomBarItem(titles[0], icons[0]),
            _bottomBarItem(titles[1], icons[1]),
            _bottomBarItem(titles[2], icons[2]),
            _bottomBarItem(titles[3], icons[3]),
          ],
          currentIndex: _currentIndex,
          type: BottomNavigationBarType.fixed,// 當items大於3時須要設置此類型
          onTap: _bottomBarItemClick,
          selectedFontSize: 12,
        );
      }
      // 建立item
      BottomNavigationBarItem _bottomBarItem(String title, String iconName,) {
        return BottomNavigationBarItem(
          icon: _image(iconName),
          title: Text(title),
          activeIcon: _image('${iconName}_select'),
          backgroundColor: Colors.white,
        );
      }
      //image
      Widget _image(String iconName) {
        return Image.asset(
          'assets/images/${iconName}@2x.png',// 在項目中添加圖片文件夾
          width: 24,
          height: 24,
        );
      }
      //item點擊事件
      _bottomBarItemClick(int index) {
        setState(() {
          _currentIndex = index;
        });
      }

調用構建方法spa

// 當前選中的索引
    int _currentIndex = 0;
    
      //item點擊事件
      _bottomBarItemClick(int index) {
        setState(() {
          _currentIndex = index;
        });
      }
      // 數據
      List titles = <String>['首頁', '收藏', '消息', '個人'];
      List icons = <String>['tabbar_discover', 'tabbar_favorite', 'tabbar_message', 'tabbar_me'];
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          bottomNavigationBar: _bottomNavigationBar(titles, icons),
        );
      }

樣式顯示code

圖片描述

相關文章
相關標籤/搜索