Flutter 仿掘金之動態Tabbar

jlanglang發表於2019-05-25

效果

Flutter 仿掘金之動態Tabbar

不多逼逼

Tabbar

先看Tabbar的引數

const TabBar({
    Key key,
    @required this.tabs, // item
    this.controller, //控制器
    this.isScrollable = false, //是否可以滑動
    this.indicatorColor, //指示器的顏色
    this.indicatorWeight = 2.0,
    this.indicatorPadding = EdgeInsets.zero,
    this.indicator,//自定義指示器
    this.indicatorSize,
    this.labelColor, // 選中文字顏色
    this.labelStyle, // 
    this.labelPadding, // 文字的內邊距
    this.unselectedLabelColor, // 未選中文字顏色
    this.unselectedLabelStyle,
    this.dragStartBehavior = DragStartBehavior.start, 
    this.onTap,// 點選事件
  })
複製程式碼

TabBarView

 const TabBarView({
    Key key,
    @required this.children, // 每頁的view
    this.controller, // 控制器
    this.physics,
    this.dragStartBehavior = DragStartBehavior.start,
  })
複製程式碼

好了,這兩個必須關聯起來用. 不然會報錯

DefaultTabController

這個是一個無狀態的控制器,很簡單.但是要做成動態Tabbar的話,不能用這個.

TabController

也很簡單.

 TabController({ int initialIndex = 0, @required this.length, @required TickerProvider vsync })
複製程式碼

主要是這個TickerProvider.作用是獲取每一幀重新整理的通知.

其實也簡單

直接 實現TickerProviderStateMixin就好了.

class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin{

  TabController _tabController;
    
  @override
  void initState() {
    super.initState();
    _tabController = new TabController(length: _spList.length, vsync: this);// 直接傳this
  }
}
複製程式碼

如何動態建立

SharedPreferences 這裡我使用了本地快取來做的

新增外掛

Flutter 仿掘金之動態Tabbar

寫個工具

class SpUtils {
  static Future<List<String>> getSpList(String key) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getStringList(key) ?? [];
  }

  static setSpList(String key, List<String> list) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setStringList(key, list);
  }
}
複製程式碼

這樣使用就簡單很多了


完整的程式碼

import 'package:flutter/material.dart';
import '../util/SpUtils.dart';

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  var _bottomIndex = 0;
  var _spList = [];
  TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = new TabController(length: _spList.length, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    SpUtils.getSpList('tabmenu').then((s) {
      if (_spList == s) {
        return;
      }
      setState(() {
        _spList = s;
        _tabController = new TabController(length: _spList.length, vsync: this);
      });
    });
    return Scaffold(
      appBar: new AppBar(
        titleSpacing: 0,
        title: Center(
          child: new TabBar(
            controller: _tabController,
            isScrollable: true,
            labelColor: Colors.white,
            tabs: _spList.map((f) {
              return Center(
                child: new Text(f),
              );
            }).toList(),
          ),
        ),
        actions: <Widget>[
          new Container(
            child: new Icon(Icons.arrow_drop_down),
            width: 48,
          )
        ],
      ),
      body: TabBarView(
          controller: _tabController,
          children: _spList.isEmpty
              ? []
              : _spList.map((f) {
                  return Center(
                    child: new Text(f),
                  );
                }).toList()),
      floatingActionButton: FloatingActionButton(
        onPressed: () {},
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
      bottomNavigationBar: new BottomNavigationBar(
        items: [
          new BottomNavigationBarItem(
            icon: Icon(Icons.home),
            title: new Container(),
          ),
          new BottomNavigationBarItem(
            icon: Icon(Icons.whatshot),
            title: new Container(),
          ),
          new BottomNavigationBarItem(
            icon: Icon(Icons.search),
            title: new Container(),
          ),
          new BottomNavigationBarItem(
            icon: Icon(Icons.book),
            title: new Container(),
          ),
          new BottomNavigationBarItem(
            icon: Icon(Icons.person),
            title: new Container(),
          ),
        ],
        currentIndex: _bottomIndex,
        type: BottomNavigationBarType.fixed,
        backgroundColor: Colors.white,
        selectedItemColor: Colors.blue,
        unselectedItemColor: Colors.grey,
        onTap: (i) {
          setState(() {
            _bottomIndex = i;
          });
        },
      ), 
    );
  }
}
複製程式碼

注意的點:

1._tabController 要重新建立.因為需要更新長度

SpUtils.getSpList('tabmenu').then((s) { //獲取快取
      if (_spList == s) {//防止遞迴重新整理
        return;
      }
      setState(() {
        _spList = s;
        _tabController = new TabController(length: _spList.length, vsync: this);
      });
    });
複製程式碼

2.Tabbar放Appbard的title位置上

TabBar需要使用center包裝.不然預設高度是不會佔滿的,當然也可以用其它辦法

isScrollable需要設定為true.才能滑動.

 appBar: new AppBar(
        titleSpacing: 0,
        title: Center(
          child: new TabBar(
            controller: _tabController,
            isScrollable: true,
            labelColor: Colors.white,
            tabs: _spList.map((f) {
              return Center(
                child: new Text(f),
              );
            }).toList(),
          ),
        ),
        actions: <Widget>[
          new Container(
            child: new Icon(Icons.arrow_drop_down),
            width: 48,
          )
        ],
      ),
複製程式碼

最後

你怎麼沒說怎麼動態的呢!

很簡單.只要更新SharedPreferences的快取值.就可以了.像 掘金的效果是跨頁面開關的.所以使用SharedPreferences的快取來做


期待你的留言 點贊

交流群:

Flutter:782978118

Android:493180098

相關文章