i am working with a flutter project in which i need to fire two diffrent code with same floating action button:
here is my tab view:
appBar: AppBar(
bottom: TabBar(indicator: BoxDecoration(
color: Colors.black12, borderRadius: BorderRadius.circular(0),
),
tabs: [
Tab(text: 'Drivers'),
Tab(text:'Cars')
],
labelColor: Colors.pink,
),
and my tab bar view:
body: TabBarView(
children:[
SingleChildScrollView(...),
Center(child: Text('add car screen'))
]
),
and a floating button:
floatingActionButton: FloatingActionButton(
onPressed: () {
// Add your onPressed code here!
},
**what i want is whenever Driver tab is selected and then i press floatingaction button it must print "driver tab selected" and whenevr i switch tab to car tab and then i press the button it prints "car tab is selected" **
please help ? Thanks in advance <3
CodePudding user response:
try to add DefaultTabController, reference:
int _currentIndex = 0;
tabController.addListener(() {
setState(() {
_currentIndex = tabController.index;
});
});
floatingActionButton: FloatingActionButton(
onPressed: () {
if(_currentIndex == 0) print('');
else print('');
},
CodePudding user response:
wrap your Scaffold inside of a Builder and you can then retrieve the tab index with DefaultTabController.of(context).index
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 2,
child: Builder(builder: (BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Tabs Demo'),
bottom: TabBar(
tabs: [
Tab(icon: Icon(Icons.contacts), text: "Drivers"),
Tab(icon: Icon(Icons.camera_alt), text: "Cars")
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
if(DefaultTabController.of(context)!.index==1)
{
print("drivers");
}
else
print("cars");
print(
'Current Index: ${DefaultTabController.of(context)!.index}');
},),
body: TabBarView(
children: [
Center(child:Text("Driver")) ,
Center(child:Text("Cars")) ,
],
),
);
}
),
)
);
}
}
Or you can also use onTap method in TabBar
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
int currentScreen=0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
title: Text('Flutter Tabs Demo'),
bottom: TabBar(
onTap:(index){
currentScreen=index;
},
tabs: [
Tab(icon: Icon(Icons.contacts), text: "Drivers"),
Tab(icon: Icon(Icons.camera_alt), text: "Cars")
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
if(currentScreen==0)
{
print("drivers");
}
else
print("cars");
},),
body: TabBarView(
children: [
Center(child:Text("Driver")) ,
Center(child:Text("Cars")) ,
],
),
)
) );
}
}