flutter TabBar设置圆角背景

flutter TabBar设置圆角背景

废话不多直接上图!

图片:
flutter TabBar设置圆角背景_第1张图片
实现思路:
利用TabController.addListener()监听页面切换时,调用setState()更新UI
使用三目设置背景即可

PS.
图中下划线可以去掉,均分间距也可改为居中,都在代码里呦~

然后上代码
代码片.

import 'package:flutter/material.dart';

class TabBarPage extends StatefulWidget {
  TabBarPage({Key key}) : super(key: key);

  @override
  _TabBarPageState createState() => _TabBarPageState();
}

class _TabBarPageState extends State<TabBarPage> with TickerProviderStateMixin {
  TabController _controller;
  List _tabs = ["全部", "进行中", "已完成"];
  int _tabIndex = 0;
  @override
  void initState() {
    super.initState();
    _controller = TabController(length: _tabs.length, vsync: this);
    _controller.addListener(() {
      print(_controller.index);
      setState(() {
        _tabIndex = _controller.index;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Container(
            color: Colors.white,
            padding: EdgeInsets.only(top: 40),
            child: TabBar(
              controller: _controller,
              // isScrollable: true,//设置为true则TabBar居中
              labelColor: Colors.white,
              unselectedLabelColor: Colors.black,
              // indicator: const BoxDecoration(),//不设置下划线
              indicator: UnderlineTabIndicator(
                borderSide: BorderSide(color: Colors.blue, width: 3),
              ),
              indicatorSize: TabBarIndicatorSize.label,
              indicatorWeight: 5.0,
              tabs: _getItem(_tabIndex),
            ),
          ),
          Flexible(
              child: TabBarView(controller: _controller, children: [
            Text("全部"),
            Text("进行中"),
            Text("已完成"),
          ]))
        ],
      ),
    );
  }

  _getItem(int index) {
    print("getItem$index");
    BoxDecoration decoration = BoxDecoration(color: Colors.white);
    List<Widget> list = [];
    for (var i = 0; i < _tabs.length; i++) {
      list.add(Container(
        margin: EdgeInsets.only(bottom: 5),
        padding: EdgeInsets.fromLTRB(5, 4, 5, 4),
        decoration: index == i
            ? BoxDecoration(
                borderRadius: BorderRadius.circular(15), color: Colors.blue)
            : decoration,
        child: Text(_tabs[i]),
      ));
    }
    return list;
  }
}

有问题的同学欢迎留言

你可能感兴趣的:(flutter,android,ios)