Adding tabs on clicking button

Issue

How can I add a new tab in TabBar by clicking on a button?

I tried to call ‘setState’ in order to add a new tab.

class _MyHomeState extends State<MyHome> {
  final List<Tab> _tabs = [
    Tab(
      child: Text("tab 1"),
    ),
    Tab(
      child: Text("tab 2"),
    )
  ];
  int _length = 2;
  final List<Widget> _tabBarView = [
    Icon(Icons.ac_unit),
    Icon(Icons.access_alarm)
  ];
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: _length,
      child: Scaffold(
        appBar: AppBar(
          title: Text("New"),
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.add),
              onPressed: () {
                setState(() {
                  _tabs.add(
                    Tab(
                      child: Text("another"),
                    ),
                  );
                  _tabBarView.add(
                    Icon(Icons.access_alarms),
                  );
                  _length = _tabs.length;
                });
              },
            ),
          ],
          bottom: TabBar(
            tabs: _tabs,
          ),
        ),
        body: TabBarView(
          children: _tabBarView,
        ),
      ),
    );
  }
}

By doing so, got an error message,

RangeError (index): Invalid value: Not in range 0..1, inclusive: 2

Solution

You need minor tweaking in your code:

change:

 bottom: TabBar(
            tabs: _tabs,
          ),
        ),
        body: TabBarView(
          children: _tabBarView,
        ),

to

  bottom: TabBar(
            tabs: _tabs.toList(),  // Creates a [List] containing the elements of this [Iterable].
          ),
        ),
        body: TabBarView(
          children: _tabBarView.toList(),  // Creates a [List] containing the elements of this [Iterable].
        ),

Answered By – anmol.majhail

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *