在使用DefaultTabController
时,我一直在尝试添加侦听器。但是,每次我添加TabController
以获取TabBar
和TabBarView
中的当前索引时,我都会失去它们之间的同步。
这是我的代码:
@override
Widget build(BuildContext context) {
return new DefaultTabController(
length: subPages.length,
child: new Scaffold(
appBar: appBar('homepage'),
body: new Center(
child: new NestedScrollView(
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
return <Widget>[
new SliverAppBar(
backgroundColor: Colors.white,
title: new TabBar(
labelColor: Colors.black,
indicatorColor: Colors.black,
labelStyle: new TextStyle(fontWeight: FontWeight.bold),
tabs: subPages.map((String str) => new Tab(text: str)).toList(),
),
),
];
},
body: new TabBarView(
children: subPages.map((String str) {
return new ListView(
padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
children: subPages.map((String str) {
return new Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: new Text(str),
);
}).toList(),
);
}).toList(),
),
),
),
floatingActionButton: new FloatingActionButton(
backgroundColor: Colors.black,
onPressed: null,
tooltip: 'Increment',
child: new Icon(Icons.add),
),
),
);
}
答案 0 :(得分:0)
我用这个:
new DefaultTabController(
child: Builder(
builder: (context) {
final tabController = DefaultTabController.of(context)!;
tabController.addListener(() {
print("New tab index: ${tabController.index}");
});
return Scaffold(
...
);
}
),
);