我想在一个脚手架的主体中包括一个TabBar(参见图片),然后在不使用TabBarView的情况下动态更改下面显示的窗口小部件。
解决此问题的最佳方法是什么?我尝试实现此解决方案:
读取TabBar的当前索引,然后使用主体中的if条件显示相应的小部件。
class _ProfileState extends State<Profile> with SingleTickerProviderStateMixin {
final List<Tab> myTabs = <Tab>[
new Tab(text: 'LEFT'),
new Tab(text: 'RIGHT'),
];
TabController _tabController;
@override
void initState() {
super.initState();
_tabController = new TabController(vsync: this, length: myTabs.length);
}
@override
Widget build(BuildContext context) {
return DefaultTabController(length: 2,
child: Scaffold(
appBar: AppBar(
title: Text('Profile'),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
// some other widgets
Container(color: Colors.white,
child: TabBar(controller: _tabController,
labelColor: Colors.grey[700],
indicatorSize: TabBarIndicatorSize.label,
indicatorColor: Colors.blueGrey[900],
tabs: myTabs,
],
),
),
(_tabController?.index == 0) ?
Container(child: Text(_tabController?.index.toString()))
: Container(child: Text(_tabController?.index.toString())),
etc
[不幸的是,_tabController?.index的值始终为null。我该如何解决?
怎么样?来自
@override
void initState() {
super.initState();
_tabController = new TabController(vsync: this, length: myTabs.length);
}
to
@override
void initState() {
super.initState();
_tabController = new TabController(vsync: this, length: myTabs.length);
_tabController.addListener(_tabSelect);
}
void _tabSelect() {
setState(() {
_currentIndex = _tabController.index;
});
}
和,来自
child: Column(
...
etc.
to
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
// some other widgets
Container(
color: Colors.white,
child: TabBar(
controller: _tabController,
labelColor: Colors.grey[700],
indicatorSize: TabBarIndicatorSize.label,
indicatorColor: Colors.blueGrey[900],
tabs: myTabs,
),
),
Container(child: Text(_currentIndex.toString()))
],
),