在点击按钮上添加标签
Adding tabs on clicking button
如何通过单击按钮在 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 (index): Invalid value: Not in range 0..1, inclusive: 2
您需要对代码进行微调:
变化:
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].
),
如何通过单击按钮在 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 (index): Invalid value: Not in range 0..1, inclusive: 2
您需要对代码进行微调:
变化:
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].
),