Home > Mobile >  How to make tab bars like buttons with space between them in flutter?
How to make tab bars like buttons with space between them in flutter?

Time:01-14

How to make tab bars like in the image below?

enter image description here

CodePudding user response:

Try this

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MyApp> with TickerProviderStateMixin {
  late int _startingTabCount;

  List<Tab> _tabs = <Tab>[];
  List<Widget> _generalWidgets = <Widget>[];
  late TabController _tabController;

  @override
  void initState() {
    _startingTabCount = 4;
    _tabs = getTabs(_startingTabCount);
    _tabController = getTabController();
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Column(
          children: <Widget>[
            Expanded(
              child: TabBarView(
                physics: NeverScrollableScrollPhysics(),
                controller: _tabController,
                children: getWidgets(),
              ),
            ),
          ],
        ),
      ),
    );
  }

  TabController getTabController() {
    return TabController(length: _tabs.length, vsync: this)
      ..addListener(_updatePage);
  }

  Tab getTab(int widgetNumber) {
    return Tab(
      icon: Column(
        children: [
          Icon(
            Icons.comment_outlined,
          ),
        ],
      ),
      text: "xxxx",
    );
  }

  Widget getWidget(int widgetNumber) {
    return Center(
      child: Text("Widget nr: $widgetNumber"),
    );
  }

  List<Tab> getTabs(int count) {
    _tabs.clear();
    for (int i = 0; i < 4; i  ) {
      _tabs.add(getTab(i));
    }
    return _tabs;
  }

  List<Widget> getWidgets() {
    _generalWidgets.clear();
    for (int i = 0; i < 4; i  ) {
      _generalWidgets.add(getWidget(i));
    }
    return _generalWidgets;
  }

  void _updatePage() {
    setState(() {});
  }

  //Tab helpers

  bool isFirstPage() {
    return _tabController.index == 0;
  }

  bool isLastPage() {
    return _tabController.index == _tabController.length - 1;
  }
}

CodePudding user response:

Try using tabbar wrapped by Expanded or else give screen width for both of them and padding between them

  Expanded(
    child: TabBar(
      labelPadding: const EdgeInsets.symmetric(horizontal: 8),
      controller: _productsTabCtr,
      isScrollable: true,
      tabs: [
        Tab(
          child: Text("All products"),
        ),
        Tab(
          child: Text("Out of Stock"),
        ),
      ],
    ),
  );
  • Related