Home > Enterprise >  How do I add background color to unselected tabs in flutter tabbar?
How do I add background color to unselected tabs in flutter tabbar?

Time:08-11

I'm making an app with a page with multiple tabs. I want it to look like this: this

I want the unselected tabs to have a white background with black font. I have managed to bring it up to this:

current progress

But I can't find an option to change the background color of unselected tabs. I have changed the text color of unselected tabs to black using the unselectedLabelColor property. I tried wrapping the tabbar widget in a container and coloring it but it just filled the entire area around it instead of just the tabs. Any idea on how I can get this without using any external packages?

CodePudding user response:

Set Scaffold backgroundColor something like backgroundColor: Colors.grey.shade100, and use TabController

class _TabBarDemoState extends State<TabBarDemo>
    with SingleTickerProviderStateMixin {
  late TabController controller = TabController(length: 10, vsync: this)
    ..addListener(() {
      setState(() {});
    });

and

TabBar(
    isScrollable: true,
    controller: controller,
    tabs: List.generate(
      10,
      (index) => AnimatedContainer(
        duration: Duration(milliseconds: 100),
        width: 34,//do as you like
        height: 34,//do as you like
        alignment: Alignment.center,
        decoration: ShapeDecoration(
          color: controller.index == index
              ? Colors.deepPurple
              : Colors.white,
          shape: CircleBorder(),
        ),
        child: Text(
          "$index",
          style: controller.index == index
              ? TextStyle()
              : TextStyle(color: Colors.black),
        ),
      ),
    )),

CodePudding user response:

ListView.separated(
  itemCount: 10,
  scrollDirection: Axis.horizontal,
  shrinkWrap: true,
  separatorBuilder: (BuildContext context, int index) => const SizedBox(width: 5,),
  itemBuilder: (context, index) {
    return GestureDetector(
      onTap: () {
        setState(() {
          isSelected = index;
        });
      },
      child: Container(
        height: 40,
        width: 40,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(25),
          color: isSelected == index ? Colors.pink : Colors.white
        ),
        child: Padding(
          padding: const EdgeInsets.all(10),
          child: Center(child: Text("${index.toString()}", style: TextStyle(color: isSelected == index ? Colors.white : Colors.black),)),
        ),
      ),
    );
  }
),
  • Related