Skip to content

Instantly share code, notes, and snippets.

@pjbelo
Last active September 26, 2022 10:21
Show Gist options
  • Save pjbelo/37f5247d9cd554059056366811b34ab4 to your computer and use it in GitHub Desktop.
Save pjbelo/37f5247d9cd554059056366811b34ab4 to your computer and use it in GitHub Desktop.
Flutter - listening to updates in TabBar when using DefaultTabController
// listening to updates in TabBar when using DefaultTabController.
import 'package:flutter/material.dart';
void main() {
runApp(TabControllerDemo());
}
class TabControllerDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 3,
child: Builder(builder: (BuildContext context) {
final TabController controller = DefaultTabController.of(context)!;
controller.addListener(() {
if (!controller.indexIsChanging) {
print(controller.index);
// add code to be executed on TabBar change
}
});
return Scaffold(
appBar: AppBar(
bottom: const TabBar(
tabs: [
Tab(text: "Tab 0"),
Tab(text: "Tab 1"),
Tab(text: "Tab 2"),
],
),
title: const Text('Tabs Demo'),
),
body: const TabBarView(
children: [
Center(child: Text('View 0')),
Center(child: Text('View 1')),
Center(child: Text('View 2')),
],
),
);
})),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment