Reputation: 1955
In the onPressed for my fab, I want to know the index of the tab that is currently selected in my DefaultTabController. How do I do this?
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'pari',
debugShowCheckedModeBanner: false,
theme: widget._themeData,
home: DefaultTabController(
length: widget._tabs.length,
child: Scaffold(
appBar: AppBar(
title: Text('pari'),
bottom: TabBar(
isScrollable: true,
tabs: widget._tabs,
),
),
body: _buildBody(),
floatingActionButton: FloatingActionButton(
onPressed: addWagerTap,
),
)
),
);
}
Upvotes: 18
Views: 17286
Reputation: 174
You can also get the index of the tab by using the onTap property of the DefaultTabController.
Widget build(BuildContext context) {
return new MaterialApp(
title: 'pari',
debugShowCheckedModeBanner: false,
theme: widget._themeData,
home: DefaultTabController(
length: widget._tabs.length,
child: Scaffold(
appBar: AppBar(
title: Text('pari'),
bottom: TabBar(
isScrollable: true,
onTap: (int index) {
print('index is $index');
}
tabs: widget._tabs,
),
),
body: _buildBody(),
floatingActionButton: FloatingActionButton(
onPressed: addWagerTap,
),
)
),
);
}
Upvotes: 7
Reputation: 6846
If you wrap your Scaffold
inside of a Builder
, you'll be able to access your DefaultTabController
within the proper context
. You can then retrieve the tab index with DefaultTabController.of(context).index
.
Widget build(BuildContext context) {
return new MaterialApp(
title: 'pari',
debugShowCheckedModeBanner: false,
theme: widget._themeData,
home: DefaultTabController(
length: 4,
child: Builder(builder: (BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('pari'),
bottom: TabBar(
isScrollable: true,
tabs: [Text('0'), Text('1'), Text('2'), Text('3')]),
),
body: _buildBody(),
floatingActionButton: FloatingActionButton(
onPressed: () {
print(
'Current Index: ${DefaultTabController.of(context).index}');
},
),
);
}),
),
);
}
Upvotes: 31