Last active
March 5, 2025 14:35
-
-
Save gabbygreat/90f5f2f2fd906042e8ff95d03ec33316 to your computer and use it in GitHub Desktop.
Tabbar controller listenable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import 'package:flutter/material.dart'; | |
| void main() { | |
| runApp( | |
| MaterialApp( | |
| theme: ThemeData( | |
| useMaterial3: false, | |
| ), | |
| home: const CustomTabSwipeControl(), | |
| ), | |
| ); | |
| } | |
| class CustomTabSwipeControl extends StatefulWidget { | |
| const CustomTabSwipeControl({super.key}); | |
| @override | |
| State<CustomTabSwipeControl> createState() => _CustomTabSwipeControlState(); | |
| } | |
| class _CustomTabSwipeControlState extends State<CustomTabSwipeControl> | |
| with SingleTickerProviderStateMixin { | |
| late TabController tabController; | |
| late ValueNotifier<int> index; | |
| late List<String> items; | |
| @override | |
| void initState() { | |
| super.initState(); | |
| items = ['FIRST', 'SECOND', 'THIRD']; | |
| tabController = TabController(length: items.length, vsync: this); | |
| index = ValueNotifier(tabController.index); | |
| tabController.animation!.addListener(_updateIndex); | |
| } | |
| void _updateIndex() { | |
| index.value = tabController.animation!.value.round(); | |
| } | |
| @override | |
| void dispose() { | |
| index.dispose(); | |
| tabController.dispose(); | |
| super.dispose(); | |
| } | |
| @override | |
| Widget build(BuildContext context) { | |
| return ValueListenableBuilder( | |
| valueListenable: index, | |
| builder: (context, position, _) { | |
| return Scaffold( | |
| appBar: AppBar( | |
| elevation: 0, | |
| bottom: TabBar( | |
| controller: tabController, | |
| indicator: const BoxDecoration(), | |
| tabs: [ | |
| // RED IS THE SELECTED INDEX | |
| // ORANGE IS THE UNSELECTED INDEX | |
| ...items.map( | |
| (e) { | |
| final indx = items.indexOf(e); | |
| bool isSelected = position == indx; | |
| return Tab( | |
| child: AnimatedContainer( | |
| duration: const Duration(milliseconds: 100), | |
| color: isSelected ? Colors.red : Colors.orange, | |
| alignment: Alignment.center, | |
| child: Text(e), | |
| ), | |
| ); | |
| }, | |
| ) | |
| ], | |
| ), | |
| ), | |
| body: TabBarView( | |
| controller: tabController, | |
| children: [ | |
| ...items.map( | |
| (e) => Center( | |
| child: Text('$e CONTENT'), | |
| ), | |
| ), | |
| ], | |
| ), | |
| ); | |
| }, | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment