Fiutter- 案例2 (Home頁面)

前言

Home頁面是通過BottomNavigationBar去進(jìn)行切換的宿稀,當(dāng)BottomNavigationBar選中第一個(gè)的時(shí)候則會(huì)打開我們的Home頁面

Home頁面

微信圖片_20220604120715.jpg

創(chuàng)建Home頁面

首先需要?jiǎng)?chuàng)建Home頁面在BottomNavigationBar切換到第一個(gè)的時(shí)候展示哈垢,而且在實(shí)際使用中,我們不希望每次切換到HomePage都創(chuàng)建一個(gè)新的惫霸,而是需要它持久化猫缭,所以我們的Body部分需要使用到PageView

創(chuàng)建一個(gè)空的HomePage

class HomePage extends StatefulWidget {

  @override
  State<StatefulWidget> createState() {
    return HomePageState();
  }
}

class HomePageState extends State with SingleTickerProviderStateMixin {

  @override
  Widget build(BuildContext context) {
    return Text('Home');
  }

}

修改下之前創(chuàng)好的Mainpage

class MainPage extends StatefulWidget {
  final String title;
  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  int currentIndex = 0;

  var _pageController = PageController();

  var pages = <Widget>[
    HomePage(),
    Text('1'),
    Text('2'),
    Text('3'),
    Text('4'),
  ];

  void onNavigationChanged(int index) {
    setState(() {
      currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.

    return Scaffold(
      body: PageView.builder(
        physics: NeverScrollableScrollPhysics(),
        itemBuilder: (context, index) => pages[index],
        controller: _pageController,
        itemCount: pages.length,
        onPageChanged: onNavigationChanged,
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(icon: Icon(Icons.home), label: '首頁'),
          BottomNavigationBarItem(icon: Icon(Icons.book), label: '書影音'),
          BottomNavigationBarItem(icon: Icon(Icons.group), label: '小組'),
          BottomNavigationBarItem(icon: Icon(Icons.store), label: '市集'),
          BottomNavigationBarItem(icon: Icon(Icons.person), label: '我')
        ],
        currentIndex: currentIndex,
        unselectedItemColor: Colors.grey,
        selectedItemColor: Colors.green,
        type: BottomNavigationBarType.fixed,
        onTap: (index){
          _pageController.jumpToPage(index);
        },
      ),
    );
  }
}

其中currentIndex表示BottomNavigationBar當(dāng)前切換到位置的一個(gè)狀態(tài)

使用PageView.builder去構(gòu)建一個(gè)PageView
physics: NeverScrollableScrollPhysics()表示不允許左右滑動(dòng)
itemBuilder表示當(dāng)前PageView需要根據(jù)Index顯示什么內(nèi)容,這里的index指的是PageView
itemCount表示頁面的數(shù)量
onPageChanged 表示當(dāng)頁面改變的時(shí)候會(huì)回調(diào)的函數(shù)壹店,我們?cè)O(shè)置了不能滑動(dòng)猜丹,所以頁面切換只能是手動(dòng)的

BottomNavigationBar中的onTap我們通過PageController手動(dòng)切換了PageView的頁面

此時(shí)當(dāng)BottomNavigationBar默認(rèn)選中第一個(gè)的時(shí)候就會(huì)打開HomePage(),并且重復(fù)切換不會(huì)創(chuàng)建新的HomePage實(shí)例硅卢,這樣就可以保存HomePage的狀態(tài)

HomePage

AppBar
頂部是使用AppBar構(gòu)成的射窒,并且可以左右切換的動(dòng)態(tài),推薦也是AppBar的一部分将塑,所以我們首先需要對(duì)AppBar進(jìn)設(shè)置

class HomePageState extends State with SingleTickerProviderStateMixin,AutomaticKeepAliveClientMixin {
  TabController? _tabController;
  
  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
  }

  @override
  void dispose() {
    _tabController?.dispose();
    super.dispose();
  }

  AppBar homePageAppBar() {
    return AppBar(
        backgroundColor: Colors.white,
        elevation: 1,
        leading: Icon(Icons.menu, color: Colors.green),
        actions: [
          Container(
            alignment: Alignment.center,
            child: Icon(Icons.mail_outline, color: Colors.green),
            padding: EdgeInsets.only(left: 16, right: 16),
          )
        ],
        centerTitle: true,
        titleSpacing: 0,
        title: GestureDetector(
          child: Container(
            height: 35,
            alignment: Alignment.center,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(10)),
                color: Color(0x12000000)),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.search,
                  color: Colors.black26,
                ),
                Text('絕命律師 第六季',
                    style: TextStyle(color: Colors.black26, fontSize: 15))
              ],
            ),
          ),
          onTap: () => {},
        ),
        bottom:   PreferredSize(
            preferredSize: const Size.fromHeight(45),
            child: Container(
                alignment: Alignment.centerLeft,
                child: TabBar(
                  isScrollable: true,
                  controller: _tabController,
                  labelColor: Colors.black,
                  indicatorColor: Colors.black,
                  indicatorSize: TabBarIndicatorSize.label,
                  labelStyle:
                  TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                  unselectedLabelStyle:
                  TextStyle(fontSize: 20, fontWeight: FontWeight.normal),
                  labelPadding: EdgeInsets.only(left: 20, right: 20),
                  tabs: [Tab(text: '動(dòng)態(tài)'), Tab(text: '推薦')],
                ))));
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
        appBar: homePageAppBar(),
        body: TabBarView(
          children: [Tab(text: '動(dòng)態(tài)'), Tab(text: '推薦')],
          controller: _tabController,
        ));
  }

  @override
  bool get wantKeepAlive => true;
}

homePageAppBar函數(shù)是用來返回一個(gè)AppBar的對(duì)象,分別設(shè)置了這些主要屬性

backgroundColor 背景顏色
elevation 陰影高度
leading 左邊widget
actions 右邊的widget
titleSpacing title左右的距離
centerTitle title是否居中
title title的widget

還有一個(gè)比較重要的bottm屬性是用來設(shè)置TabBar的樣式脉顿,我們一般也可以直接返回一個(gè)TabBar默認(rèn)是直接橫向撐開并且居中的,但是由于我們的TabBar是一個(gè)居左的樣式所以做了個(gè)限定

Body
Body部分就屬于TabBar的切換內(nèi)容点寥,所以在body部分直接使用了可以合TabBar聯(lián)動(dòng)的TabBarView即可艾疟,他們使用一個(gè)相同的Controller

歡迎關(guān)注Mike的簡(jiǎn)書

Android 知識(shí)整理

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市敢辩,隨后出現(xiàn)的幾起案子蔽莱,更是在濱河造成了極大的恐慌,老刑警劉巖戚长,帶你破解...
    沈念sama閱讀 219,490評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件碾褂,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡历葛,警方通過查閱死者的電腦和手機(jī)正塌,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來恤溶,“玉大人乓诽,你說我怎么就攤上這事≈涑蹋” “怎么了鸠天?”我有些...
    開封第一講書人閱讀 165,830評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長帐姻。 經(jīng)常有香客問我稠集,道長奶段,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,957評(píng)論 1 295
  • 正文 為了忘掉前任剥纷,我火速辦了婚禮痹籍,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘晦鞋。我一直安慰自己蹲缠,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,974評(píng)論 6 393
  • 文/花漫 我一把揭開白布悠垛。 她就那樣靜靜地躺著线定,像睡著了一般。 火紅的嫁衣襯著肌膚如雪确买。 梳的紋絲不亂的頭發(fā)上斤讥,一...
    開封第一講書人閱讀 51,754評(píng)論 1 307
  • 那天,我揣著相機(jī)與錄音湾趾,去河邊找鬼芭商。 笑死,一個(gè)胖子當(dāng)著我的面吹牛撑帖,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播澳眷,決...
    沈念sama閱讀 40,464評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼胡嘿,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了钳踊?” 一聲冷哼從身側(cè)響起衷敌,我...
    開封第一講書人閱讀 39,357評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎拓瞪,沒想到半個(gè)月后缴罗,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,847評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡祭埂,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,995評(píng)論 3 338
  • 正文 我和宋清朗相戀三年面氓,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蛆橡。...
    茶點(diǎn)故事閱讀 40,137評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡舌界,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出泰演,到底是詐尸還是另有隱情呻拌,我是刑警寧澤,帶...
    沈念sama閱讀 35,819評(píng)論 5 346
  • 正文 年R本政府宣布睦焕,位于F島的核電站藐握,受9級(jí)特大地震影響靴拱,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜猾普,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,482評(píng)論 3 331
  • 文/蒙蒙 一袜炕、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧抬闷,春花似錦妇蛀、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至炕泳,卻和暖如春纵诞,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背培遵。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評(píng)論 1 272
  • 我被黑心中介騙來泰國打工浙芙, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人籽腕。 一個(gè)月前我還...
    沈念sama閱讀 48,409評(píng)論 3 373
  • 正文 我出身青樓嗡呼,卻偏偏與公主長得像,于是被迫代替她去往敵國和親皇耗。 傳聞我的和親對(duì)象是個(gè)殘疾皇子南窗,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,086評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容