See the attached sample code. If I clear the state when changing tabs by using TabBar onTap, the updated state is not reflected in the TabBarViews.
In my sample code, clicking on the buttons in the TabBarViews sets state which highlights the button. When changing tabs, the buttons in the tabs should no longer be highlighted, but they still are.
import 'package:flutter/material.dart';
void main() {
runApp(const TabBarDemo());
}
class TabBarDemo extends StatefulWidget {
const TabBarDemo({super.key});
@override
State<TabBarDemo> createState() => _TabBarDemoState();
}
class _TabBarDemoState extends State<TabBarDemo> {
int state = 0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
tabs: const [
Tab(text: 'One'),
Tab(text: 'Two'),
],
onTap: (value) {
setState(() => state = 0);
},
),
title: const Text('Tabs Demo'),
),
body: TabBarView(
children: [
Center(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: (state == 1) ? Colors.blue : Colors.grey,
),
onPressed: () {
setState(() => state = 1);
},
child: const Text('One'),
),
),
Center(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: (state == 2) ? Colors.blue : Colors.grey,
),
onPressed: () {
setState(() => state = 2);
},
child: const Text('Two'),
),
),
],
),
),
),
);
}
}
3
Answers
SetState is not needed here infact stateless widget can do that task. Have a look here and in the body try to implement like this only. I have attached an image for you
Actually, this was an issue that has been recently fixed by the flutter team. You can have a look at it here.
If you will copy your code to dartpad but use the master channel instead of stable, you will notice that it works as expected. You can try it here
I presume the flutter team will merge this into the next stable release.
In your IDE terminal you can use this:
flutter channel master
and then
flutter run
Alternatively, if you want to run the stable channel you could make use of Provider for state management.
Instead of this
Use this :
Now Assign the Controller into Your View then it will work