我正在使用Flutter Default Tab Controller显示标签 View 。而且我需要在单击按钮时更改选项卡,我尝试使用setState更改选项卡,但失败了。这些是我的代码:
class _TabPageState extends State<TabPage> implements TabView {
int tabIndex = 0;
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 4,
initialIndex: tabIndex,
child: Scaffold(
appBar: AppBar(),
body: TabBarView(
physics: NeverScrollableScrollPhysics(),
children: [
Container(
color: Colors.green,
child: Center(
child: RaisedButton(
child: Text('to Tab 3'),
onPressed: () {
setState(() {
tabIndex = 2;
});
}),
),
),
Container(color: Colors.red),
Container(color: Colors.yellow),
Container(color: Colors.cyan),
],
),
bottomNavigationBar: TabBar(
labelColor: Colors.black45,
tabs: [
Padding(padding: const EdgeInsets.only(top: 12, bottom: 12), child: Text('green')),
Padding(padding: const EdgeInsets.only(top: 12, bottom: 12), child: Text('red')),
Padding(padding: const EdgeInsets.only(top: 12, bottom: 12), child: Text('yellow')),
Padding(padding: const EdgeInsets.only(top: 12, bottom: 12), child: Text('cyan')),
],
),
),
);
}
}
最佳答案
试试这个:
import 'package:flutter/material.dart';
class TabExample extends StatefulWidget {
@override
_TabExampleState createState() => _TabExampleState();
}
class _TabExampleState extends State<TabExample> {
var tabIndex = 0;
@override
Widget build(BuildContext context) {
var childList = [
Container(
color: Colors.green,
child: Center(
child: RaisedButton(
child: Text('to Tab 3'),
onPressed: () {
setState(() {
tabIndex = 2;
});
}),
),
),
Container(color: Colors.red),
Container(color: Colors.yellow),
Container(color: Colors.cyan),
];
return DefaultTabController(
length: 4,
initialIndex: tabIndex,
child: Scaffold(
appBar: AppBar(),
body: childList[tabIndex],
bottomNavigationBar: TabBar(
onTap: (index) {
setState(() {
tabIndex = index;
});
},
labelColor: Colors.black,
tabs: <Widget>[
Tab(text: 'Green'),
Tab(text: 'Red'),
Tab(text: 'Yellow'),
Tab(text: 'Cyan'),
],
),
),
);
}
}
关于flutter - 如何在Flutter默认选项卡 Controller 中更改选项卡?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59926907/