flutter TabBar set rounded background

flutter TabBar set rounded background

Not much nonsense, go directly to the picture!

Picture:
Insert picture description here
Implementation ideas:
Use TabController.addListener() to monitor page switching, call setState() to update the UI and
use trinocular to set the background

PS. The
underline in the figure can be removed, and the even spacing can also be changed to center, all in the code~

Then on the code
代码片.

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;
  }
}

Students with questions are welcome to leave a message

Guess you like

Origin blog.csdn.net/guchengjiumeng/article/details/111681773