0

如何通过单击按钮在 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

4

1 回答 1

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].
        ),
于 2019-08-12T11:19:43.207 回答