我已经尝试了很多次,但我无法让flutter TabBar AnimateTo(切换到其他页面的代码)工作。我尝试过很多不同的例子。我将函数 setTabView(int) 传递给子页面,并在该页面上更改页面索引。它触发了,但没有任何反应。保持在同一页面上。
我还想知道,是否可以从其他子页面以编程方式修改选项卡栏顶部的文本(标题)?主页面上的示例我想将标题设置为“欢迎”并更改为第二页我想将标题设置为“第二页”。我尝试使用名为 setTekst 的函数(在我的代码中)来完成此操作,但它不能完全工作。
我的代码顶部
class HovedSideTab extends StatefulWidget {
@override
State<HovedSideTab> createState() => _HovedSideTabState();
}
我的标签代码
class _HovedSideTabState extends State<HovedSideTab> with SingleTickerProviderStateMixin {
late TabController _tabController;
int _selectedIndex = 0;
String headerTekst = "";
void setTabView(int nr) {
log().prnt("hovedsidetab", "Går til tab ${nr} ${_tabController.index}");
setState(() {
_tabController.animateTo(nr);
});
}
@override
void initState() {
super.initState();
_tabController = new TabController(vsync: this, length: 5);
});
super.initState();
}
void setTekst(String tekst) {
setState(() {
headerTekst = tekst;
});
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
child: Scaffold(
backgroundColor: appBakgrunnsFarge,
body: DefaultTabController(
length: 5,
child: Scaffold(
appBar: AppBar(
centerTitle: true,
elevation: 0,
bottom: TabBar(
tabs: [
Tab(icon: Icon(Icons.home)),
Tab(icon: Icon(Icons.apartment)),
Tab(icon: Icon(Icons.help)),
Tab(icon: Icon(Icons.local_parking_rounded)),
Tab(icon: Icon(Icons.question_mark)),
],
),
actions: <Widget>[
IconButton(onPressed: () { Navigator.push(context,MaterialPageRoute(builder: (context) => OmAppen()),); }, icon: Icon(Icons.help, color: iconColor, size: iconSize,),),
IconButton(onPressed: () { Navigator.push(context,MaterialPageRoute(builder: (context) => MinSide()),); }, icon: Icon(Icons.settings, color: iconColor, size: iconSize,),),
],
title: Text('Park'),
),
body: TabBarView(
children: [
Container(child: HovedSide(), ),
Container(child: VelgSameie()),
Container(child: SameieOgPlassReg()),
Container(child: Ledig(callback: setTabView)),
Container(child: Onskes()),
],
),
),
),
),
);
}
}
我用谷歌搜索并尝试了很多不同的例子
您必须将
_tabController
传递给 controller
的 TabBar
参数。
TabBar(
controller: _tabController,
// ...
)
而且您不需要用
_tabController.animateTo(nr);
包裹 setState
。
参见:TabBar 类