单击按钮添加选项卡

时间:2019-08-12 09:54:37

标签: flutter flutter-appbar

如何通过单击按钮在TabBar中添加新标签?

我试图调用“ setState”以添加新标签。

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

这样做,收到一条错误消息,

  

RangeError(索引):无效值:不在0..1范围内(包括2)

1 个答案:

答案 0 :(得分:0)

您需要对代码进行些微调整:

更改:

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

  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].
        ),
相关问题