使用 flutter 實現一個底部導航欄

現現在打開一個 App,好比微信、支付寶,都能看到一個底部導航欄,用來切換到不一樣的展現頁。今天就用 Flutter 實現一下這種效果。html


在 Flutter 裏,基本上全部的東西都是組件。Flutter 也已經有了現成的底部導航欄組件了 -- BottomNavigationBar,因此用 Flutter 實現底部導航,實際上是很簡單地一件事情,只須要知道怎麼使用就行了。git

  1. 首先,利用 IDE 實現代碼大體的結構
import 'package:flutter/material.dart';

class BottomNav extends StatefulWidget {
  @override
  _BottomNavState createState() => _BottomNavState();
}

class _BottomNavState extends State<BottomNav> {
  @override
  Widget build(BuildContext context) {
    return Container(

    );
  }
}
複製代碼

筆者用的是 vs code,而後有安裝 flutter 、dart 的插件。要實現上述的結構,只要在編輯器中輸入 stful,而後就會有提示出來了,如圖所示: github

vs code 編輯器會 dart 的支持是十分友好的了,也有不少提示,在編碼時能夠充分利用。目前惟一的缺點應該就是缺乏 flutter inspector 了。微信

  1. 實現_BottomNavState 的 build 方法
class _BottomNavState extends State<BottomNav> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Bottom Navigation Demo')),
      bottomNavigationBar: BottomNavigationBar(
        items: [
          BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('Home')),
          BottomNavigationBarItem(icon: Icon(Icons.business), title: Text('Business')),
          BottomNavigationBarItem(icon: Icon(Icons.school), title: Text('School')),
        ],
        fixedColor: Colors.green,
        currentIndex: 0,
        onTap: (int idx) {}
      ),
    );
  }
}
複製代碼

這時候,用仿真器看到的效果以下: app

  1. 添加交互

到這裏,咱們已經實現了大概的效果,可是你會發現,點擊底部的圖標切換,是沒有效果的。如今,就給底部導航添加交互行爲。編輯器

  • 定義變量_currentIndex,並將 BottomNavagationBar 的 currentIndex 的值用變量 _currentIndex 代替
int _currentIndex = 0;
複製代碼
  • 實現 BottomNavagationBar 的 onTap 方法
void onItemTapped(int idx) {
  setState(() {
    _currentIndex = idx;
  })
}
複製代碼

至此,就完成了底部導航欄的功能啦。ide

完成代碼請看這裏 bottom_navagation_bar.dart學習

最後

筆者最近在學習flutter,會持續地記錄本身的學習過程,並放在 github 上。ui

有問題歡迎提出,你們一塊兒討論,一塊兒進步。編碼

參考資料

BottomNavigationBar class

相關文章
相關標籤/搜索