I am using a TabBarView with class items:
TabBarView(
controller: _tabController,
children: const [
ListaCatTareas(),
ListaSubCatTareas(),
ListaTiposTareas(),
],
),
I would like to change the active tabbar index from inside of all the children widgets.
For example, I have selected to open the widget at index 1, which is ListaSubCatTareas, then inside of this widget I may need to change the tabbar active index to 0 or 2.
CodePudding user response:
You can use tabController.index
to change the tab bar active index. check running below code.
import 'package:flutter/material.dart';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: TabBarSampleClass(),
),
),
);
}
}
class TabBarSampleClass extends StatefulWidget {
@override
_TabBarSampleClassState createState() => _TabBarSampleClassState();
}
class _TabBarSampleClassState extends State<TabBarSampleClass>
with SingleTickerProviderStateMixin {
late final _tabController = TabController(length: 3, vsync: this);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Tab Navigation'),
bottom: TabBar(
controller: _tabController,
tabs: const <Widget>[
Tab(
icon: Icon(Icons.book, color: Colors.white),
text: 'TabOne',
),
Tab(
icon: Icon(Icons.chat, color: Colors.white),
text: 'TabTwo',
),
Tab(
icon: Icon(Icons.access_alarm, color: Colors.white),
text: 'TabThree',
),
],
),
),
body: TabBarView(
controller: _tabController,
children: [
IconButton(
icon: const Icon(
Icons.arrow_circle_right,
),
iconSize: 50,
color: Colors.green,
splashColor: Colors.purple,
onPressed: () {
//Navigate to tab 2
_tabController.index = 1;
},
),
IconButton(
icon: const Icon(
Icons.arrow_circle_right,
),
iconSize: 50,
color: Colors.green,
splashColor: Colors.purple,
onPressed: () {
//Navigate to tab 3
_tabController.index = 2;
},
),
IconButton(
icon: const Icon(
Icons.arrow_circle_right,
),
iconSize: 50,
color: Colors.green,
splashColor: Colors.purple,
onPressed: () {
//Navigate to tab 1
_tabController.index = 0;
},
),
],
),
);
}
}
or if you are using CustomWidgetClass, pass the _tabController object to the custom widget and navigate by same _tabController.index = 2;
CustomClassForThridTab(
tabcontroller: _tabController
),