I have used different approach. I have used flutter_bloc to achieve this. To understand this approach first see https://pub.dev/packages/flutter_bloc
Note: If you are using cubits then don't forget to close() them
First I created a cubit class as:
import 'package:flutter_bloc/flutter_bloc.dart';
class UICubit<T> extends Cubit<T> {
T currentState;
UICubit(T state) : super(state);
void updateState(T newState) {
this.currentState = newState;
emit(currentState);
}
}
After that I have created a TabIcon Class as below:
class TabIcon extends StatelessWidget {
final Color selectedColor;
final Color unselectedColor;
final Icon icon;
final double size;
final UICubit<bool> uiCubit;
TabIcon(this.uiCubit, this.icon, this.selectedColor, this.unselectedColor,
this.size);
@override
Widget build(BuildContext context) {
return BlocConsumer<UICubit<bool>, bool>(
cubit: uiCubit,
listener: (BuildContext context,bool flag) {},
builder: (BuildContext context, bool flag) {
return _buildImage(flag?selectedColor:unselectedColor);
},
);
}
Widget _buildImage(int color) {
return Image.asset(
icon,
width: size,
height: size,
color: color,
);
}
}
Now in Parent Widget I created a list of cubits as below:
List<UICubit<TabState>> cubitList = [];
Adding Tabs:
List<Tab> tabs = [];
cubit1 = UICubit<TabState>(true);
cubitList.add(cubit1);
tabs.add(Tab(
text: "First",
icon: TabIcon(cubit1, Icons.firsIcon, Colors.blue,Colors.grey),
),
cubit2 = UICubit<TabState>(false);
cubitList.add(cubit2);
tabs.add(Tab(
text: "Second",
icon: TabIcon(cubit2, Icons.firsIcon, Colors.blue,Colors.grey),
),
Now on tab Click:
TabBar(
onTap: (index) {
updateTab(index);
},
tabs: tabs,
),
updateTab() mehtod:
void updateTab(int index) async {
for (int i = 0; i < cubitList.length; i++) {
if (i == index) {
cubitList[i].updateState(true);
} else {
cubitList[i].updateState(false);
}
}
}
Don't forget to close your cubits in dispose method of parent widget:
@override
void dispose() {
cubitList.forEach((element) {
element.close();
});
super.dispose();
}
Thanks, May be some people don't like this approach but this approach solved my problem.