I am trying to display the tab number on each page of a TabBarView, by reading the index of its TabController. For some reason though, the value does not seem to update correctly visually, even though the correct value is printed in the logs.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
TabController? _tabController;
#override
void initState() {
super.initState();
_tabController = TabController(
length: 3,
vsync: this,
);
}
_back() {
if (_tabController!.index > 0) {
_tabController!.animateTo(_tabController!.index - 1);
setState(() {});
}
}
_next() {
if (_tabController!.index < _tabController!.length - 1) {
_tabController!.animateTo(_tabController!.index + 1);
setState(() {});
}
}
Widget _tab(int index) {
var value = "Page $index: ${_tabController!.index + 1} / ${_tabController!.length}";
print(value);
return Row(
children: [
TextButton(
onPressed: _back,
child: const Text("Back"),
),
Text(value,
style: const TextStyle(
),
),
TextButton(
onPressed: _next,
child: const Text("Next"),
),
],
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: TabBarView(
controller: _tabController,
children: [
_tab(1),
_tab(2),
_tab(3),
],
)
);
}
}
When navigating from index 0 to index 1, the following is printed in the logs, as expected:
I/flutter (25730): Page 1: 2 / 3
I/flutter (25730): Page 2: 2 / 3
I/flutter (25730): Page 3: 2 / 3
However, what is actually displayed is Page 2: 1 / 3
I have tried using UniqueKey as well as calling setState on the next frame, but it doesn't make a difference. Calling setState with a hardcoded delay seems to work, but it also seems wrong.
Why is what's printed in the logs different to what's being displayed, considering that all tabs are rebuilt when setState is called? Assuming it has something to do with the PageView/Scrollable/Viewport widgets that make up the TabBarView, but what exactly is going on? Notice how even when going from page 1 to page 2 and then to page 3, none of the values on any of the pages are being updated, so even the on-screen widgets aren't rebuilding correctly.
I am finally able to answer my own question. This odd behaviour is explained by the internal logic of the _TabBarViewState. The TabBarView uses a PageView internally, which it animates based on changes to the TabController index. Here is a snippet of that logic:
final int previousIndex = _controller!.previousIndex;
if ((_currentIndex! - previousIndex).abs() == 1) {
_warpUnderwayCount += 1;
await _pageController.animateToPage(_currentIndex!, duration: kTabScrollDuration, curve: Curves.ease);
_warpUnderwayCount -= 1;
return Future<void>.value();
}
Note that it keeps track of whether an animation is in progress with the _warpUnderwayCount variable, which will get a value of 1 as soon as we call animateTo() on the TabController.
Additionally, the _TabBarViewState maintains a _children list of widgets representing each page, which is first created when the TabBarView is initialized, and can later be updated only by the _TabBarViewState itself by calling its _updateChildren() function:
void _updateChildren() {
_children = widget.children;
_childrenWithKey = KeyedSubtree.ensureUniqueKeysForList(widget.children);
}
The _TabBarViewState also overrides the default behaviour of the didUpdateWidget function:
#override
void didUpdateWidget(TabBarView oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.controller != oldWidget.controller)
_updateTabController();
if (widget.children != oldWidget.children && _warpUnderwayCount == 0)
_updateChildren();
}
Note that even though we provide a new list of children from our parent stateful widget by calling setState() just after animateTo(), that list of children will be ignored by the TabBarView because _warpUnderwayCount will have a value of 1 at the point that didUpdateWidget is called, and therefore _updateChildren() will not be called as per the internal logic shown above.
I believe this is a constraint of the TabBarView widget that has to do with its complexity in terms of coordinating with its internal PageView as well as with an optional TabBar widget with which it shares a TabController.
In terms of a solution, given that rebuilding the whole TabBarView by updating its Key would cancel the animation, and that setting new children by calling setState() after calling animateTo() is ignored if done while the page change animation is still running, I can only think of calling setState() after saving all the variables required for rebuilding the children and before animateTo() is called on the next frame. If it is called within the same frame, the children will still not update because didUpdateWidget will still be called after the animation starts. Here is the code from my question, updated with the proposed solution:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
TabController? _tabController;
int _newIndex = 0;
#override
void initState() {
super.initState();
_tabController = TabController(
length: 3,
vsync: this,
);
}
_back() {
if (_tabController!.index > 0) {
_newIndex = _tabController!.index - 1;
setState(() {});
WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
_tabController!.animateTo(_newIndex);
});
}
}
_next() {
if (_tabController!.index < _tabController!.length - 1) {
_newIndex = _tabController!.index + 1;
setState(() {});
WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
_tabController!.animateTo(_newIndex);
});
}
}
Widget _tab(int index) {
var value = "Page $index: ${_newIndex + 1} / ${_tabController!.length}";
print(value);
return Row(
children: [
TextButton(
onPressed: _back,
child: const Text("Back"),
),
Text(value,
style: const TextStyle(
),
),
TextButton(
onPressed: _next,
child: const Text("Next"),
),
],
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: TabBarView(
controller: _tabController,
children: [
_tab(1),
_tab(2),
_tab(3),
],
)
);
}
}
You can use Stream to listen for tab index change when switching pages. Update the index when changing page.
final _tabPageIndicator = StreamController<int>.broadcast();
Stream<int> get getTabPage => _tabPageIndicator.stream;
...
// Update tab index on Stream
_tabPageIndicator.sink.add(_tabController!.index + 1);
Then using StreamBuilder, this gets rebuild when there's a change on the Stream it's listening to. There's no need to use setState() to rebuild the Widgets inside StreamBuilder.
StreamBuilder<int>(
stream: getTabPage,
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
if (snapshot.hasData && snapshot.data != null) {
tabIndex = snapshot.data!;
}
return Text(
'Page $index: [$tabIndex / ${_tabController!.length}]',
style: const TextStyle(),
);
}
),
Complete Sample
import 'dart:async';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
TabController? _tabController;
int tabIndex = 1;
final _tabPageIndicator = StreamController<int>.broadcast();
Stream<int> get getTabPage => _tabPageIndicator.stream;
#override
void initState() {
super.initState();
_tabController = TabController(
length: 3,
vsync: this,
);
// Update tab index on Stream
_tabPageIndicator.sink.add(_tabController!.index + 1);
}
#override
void dispose() {
super.dispose();
// Close Stream when not in use
_tabPageIndicator.close();
}
_back() {
if (_tabController!.index > 0) {
_tabController!.animateTo(_tabController!.index - 1);
// setState(() {
// });
// Update tab index on Stream
_tabPageIndicator.sink.add(_tabController!.index + 1);
}
}
_next() {
if (_tabController!.index < _tabController!.length - 1) {
_tabController!.animateTo(_tabController!.index + 1);
// setState(() {
// });
// Update tab index on Stream
_tabPageIndicator.sink.add(_tabController!.index + 1);
}
}
Widget _tab(int index) {
var value =
"Page $index: ${_tabController!.index + 1} / ${_tabController!.length}";
debugPrint(value);
return Row(
children: [
TextButton(
onPressed: _back,
child: const Text("Back"),
),
// StreamBuilder rebuilds every time there's a change on Stream
StreamBuilder<int>(
stream: getTabPage,
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
if (snapshot.hasData && snapshot.data != null) {
tabIndex = snapshot.data!;
}
return Text(
'Page $index: [$tabIndex / ${_tabController!.length}]',
style: const TextStyle(),
);
}),
TextButton(
onPressed: _next,
child: const Text("Next"),
),
],
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: TabBarView(
controller: _tabController,
children: [
_tab(1),
_tab(2),
_tab(3),
],
));
}
}
From documentation of flutter animatedTo method description: animatedTo immediately sets index and previous index and then plays the animation from its current value to index.
Once the _tab method is called, the widget that returns from it is now in the widget tree.
Whenever the build method is run again then its appearance will change.
Every time the _tab method is called, the part of the code that does not return the widget runs again, and return widget which is already in the widget tree.
But it is necessary to run the build method again for the widget to change.
The build is called when the widget is built for the first time. But after that, it is necessary to re-run the build method with setState.
I convert your tab navigation buttons to Widget class. We can more easily understand the comparison with the _tab method and Widget class.
When navigating from index 0 to index 1,2,3 the following is printed in the logs:
flutter: Page 0: 1 / 3
flutter: Page 0: 1 / 3
import 'package:flutter/material.dart';
void main() {
runApp(const TestMyApp());
}
class TestMyApp extends StatelessWidget {
const TestMyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>
with SingleTickerProviderStateMixin {
TabController? _tabController;
#override
void initState() {
super.initState();
_tabController = TabController(
length: 3,
vsync: this,
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Column(
children: [
Expanded(
child: TabBarView(
controller: _tabController,
children: [
_tab(1),
_tab(2),
_tab(3),
],
),
),
Expanded(
child: TabNavigationWidget(tabController: _tabController!)),
],
));
}
Widget _tab(int index) {
return Text('$index');
}
}
class TabNavigationWidget extends StatelessWidget {
TabController tabController;
TabNavigationWidget({Key? key, required this.tabController})
: super(key: key);
#override
Widget build(BuildContext context) {
var value = "Page : ${tabController.index + 1} / ${tabController.length}";
print(value);
return Row(
children: [
TextButton(
onPressed: _back,
child: Text("Back ${tabController.index}"),
),
Text(
value,
style: const TextStyle(),
),
TextButton(
onPressed: _next,
child: const Text("Next"),
),
],
);
}
_back() {
if (tabController.index > 0) {
tabController.animateTo(tabController.index - 1);
}
}
_next() {
if (tabController.index < tabController.length - 1) {
tabController.animateTo(tabController.index + 1);
}
}
}
I recommend to you use widgets classes instead of _tab() methods. Your _tab methods build 3 times when the setState method is called.
I know too little about widget tree feel free to correct and update the answer.
All tabs are building initially, while the _tabController!.index is 0. _next method does to wait for animateTo to finish the animation, then call setState. Using setState rebuild the UI under build but the TabBarView is not rebuilding until we are telling it that it is having changes.
widget tree is smart enough while updating the UI. -🔎
While creating a widget, without providing key it generates objectRuntimeType key, and doesn't change(same for providing key) on calling setState.
While here, update is depending on key, and widget tree(key) is not different for TabBarView and TabBarView is thinking nothing happen to me, we can't see any update on UI.
Then next comes by adding listener
Register a closure to be called when the object changes.
We can add listener on TabController to listen changes and inside setState to update the UI. You can also remove setState from _back and _next methods.
_tabController = TabController(
length: 3,
vsync: this,
)..addListener(() {
setState(() {});
});
Or just
Use index instead of _tabController!.index while both responsibility is same inside Row.
Related
I'm working on a PageView with States managed by ValueNotifier. I choose ValuNotifier because it is fast and native. The ValueListenableBuilder works great for a regular page with states like loading, success and error where the body is rebuilt with the content state.
In the code above, ValueListenableBuilder rebuild the body page when state changes, but some states should only push SnackBar and should keep the current value.
What is the best way to handler error (or warning) in SnackBar or Dialog, keeping the body page with the current state (with data, for example)?
All states (even error) carry all data to rebuild the body, than I show SnackBar and rebuild the body;
Show SnackBar by one callback, viewpage will register one controller callback and do all the process to get the context and show SnackBar;
In my point of view, the 2nd distort the ideia of state manager but avoid to rebuild body; but the 1st looks over by the fact I have to carry all information all the time and 'rebuild' everything. I think, the 1st could be a big problem if body has animated transitions.
Do you recomend a 3rd alternative?
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
// ======= Controller =======
class CounterState {}
class SuccessCounterState extends CounterState {
final int currentValue;
SuccessCounterState(this.currentValue);
}
class MaxCounterState extends CounterState {}
class MinCounterState extends CounterState {}
class Counter extends ValueNotifier<CounterState> {
Counter() : super(SuccessCounterState(0));
var _localValue = 0;
void increment() {
if (_localValue + 1 > 9) {
value = MaxCounterState();
} else {
_localValue++;
value = SuccessCounterState(_localValue);
}
}
void decrement() {
if (_localValue - 1 < 0) {
value = MinCounterState();
} else {
_localValue--;
value = SuccessCounterState(_localValue);
}
}
}
// ==== Page ====
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final counter = Counter();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
ValueListenableBuilder<CounterState>(
valueListenable: counter,
builder: (BuildContext context, state, _) {
if (state is SuccessCounterState) {
return Text(
'${state.currentValue}',
style: Theme.of(context).textTheme.headline4,
);
}
if (state is MaxCounterState) {
Future.delayed(const Duration(milliseconds: 1), () {
const snackBar =
SnackBar(content: Text('Reached the max value'));
ScaffoldMessenger.of(context).showSnackBar(snackBar);
});
}
if (state is MinCounterState) {
Future.delayed(const Duration(milliseconds: 1), () {
const snackBar =
SnackBar(content: Text('Reached the min value'));
ScaffoldMessenger.of(context).showSnackBar(snackBar);
});
}
return const SizedBox();
},
),
],
),
),
floatingActionButton: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
FloatingActionButton(
onPressed: counter.decrement,
tooltip: 'Decrement',
child: const Icon(Icons.remove),
),
const SizedBox(width: 20.0),
FloatingActionButton(
onPressed: counter.increment,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
],
),
);
}
}
I use the following code snippet to create a tab bar with 20 tabs along with their views (you can copy-paste the code to try it out, it complies with no problems):
import 'package:flutter/material.dart';
class TabBody extends StatefulWidget {
final int tabNumber;
const TabBody({required this.tabNumber, Key? key}) : super(key: key);
#override
State<TabBody> createState() => _TabBodyState();
}
class _TabBodyState extends State<TabBody> {
#override
void initState() {
print(
'inside init state for ${widget.tabNumber}'); //<--- I want this line to execute only once
super.initState();
}
getDataForTab() {
//getting data for widget.tabNumber
}
#override
Widget build(BuildContext context) {
return Center(
child: Container(
color: Colors.grey,
child: Text('This is tab #${widget.tabNumber} body')),
);
}
}
class MainPage extends StatefulWidget {
const MainPage({Key? key}) : super(key: key);
#override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
List<Text> get _tabs {
var list = [for (var i = 0; i < 20; i += 1) i];
List<Text> tabs = list.map((i) => Text('Tab Title $i')).toList();
return tabs;
}
List<TabBody> get _tabsBodies {
var list = [for (var i = 0; i < 20; i += 1) i];
List<TabBody> bodies = list.map((i) => TabBody(tabNumber: i)).toList();
return bodies;
}
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: _tabs.length,
child: Column(
children: <Widget>[
Container(
width: double.infinity,
height: 50,
color: Colors.black,
child: TabBar(
isScrollable: true,
tabs: _tabs,
),
),
Expanded(
child: TabBarView(
children: _tabsBodies, //<--- i want this to be one child only
),
)
],
),
);
}
}
I need to do the following but couldn't find a way for that:
I want to let the TabBarView to have only one child of type TabBody not a list of _tabsBodies, i.e. the print statement in initState should execute once.
I want to execute the function getDataForTab every time the tab is changed to another tab.
so in general I need to refresh the tab body page for each tab selection, in contrast to the default implementation of the DefaultTabController widget which requires to have n number of tab bodies for n number of tabs.
You'll need to do three things:
Remove the TabBarView. You don't need it if you want to have a single widget. (Having a TabBar does not require you to have a TabBarView)
Create your own TabController so you can pass the current index to the TabBody.
Listen to the TabController and update the state to pass the new index to TabBody.
Here's a fully runnable example and that you can copy and paste to DartPad
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
const MyHomePage({
Key? key,
required this.title,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: MainPage(),
);
}
}
class MainPage extends StatefulWidget {
const MainPage({Key? key}) : super(key: key);
#override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage>
with SingleTickerProviderStateMixin {
late final tabController =
TabController(length: 20, vsync: this, initialIndex: 0);
#override
void initState() {
super.initState();
tabController.addListener(() {
if (tabController.previousIndex != tabController.index && !tabController.indexIsChanging) {
print('setting state'); // <~~ will print one time now
setState(() {});
}
});
}
List<Text> get _tabs {
var list = [for (var i = 0; i < 20; i += 1) i];
List<Text> tabs = list.map((i) => Text('Tab Title $i')).toList();
return tabs;
}
#override
void dispose() {
tabController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Container(
width: double.infinity,
height: 50,
color: Colors.black,
child: TabBar(
isScrollable: true, tabs: _tabs, controller: tabController),
),
Expanded(
child: TabBody(tabNumber: tabController.index),
)
],
);
}
}
class TabBody extends StatefulWidget {
final int tabNumber;
const TabBody({required this.tabNumber, Key? key}) : super(key: key);
#override
State<TabBody> createState() => _TabBodyState();
}
class _TabBodyState extends State<TabBody> {
#override
void initState() {
print(
'inside init state for ${widget.tabNumber}'); //<--- I want this line to execute only once
super.initState();
}
getDataForTab() {
//getting data for widget.tabNumber
}
#override
Widget build(BuildContext context) {
return Center(
child: Container(
color: Colors.grey,
child: Text('This is tab #${widget.tabNumber} body')),
);
}
}
Few notes about the example:
when you create a TabController, you'll need a ticker. You can use SingleTickerProviderStateMixin to make the class itself a ticker (hence: vsync: this). Alternatively, you can create your own and pass it to TabController.vsync parameter.
class _MainPageState extends State<MainPage> with SingleTickerProviderStateMixin {
late final tabController = TabController(length: 20, vsync: this, initialIndex: 0);
Here we are listening to the tab controller whenever the tabs changes:
#override
void initState() {
super.initState();
tabController.addListener(() {
if (tabController.previousIndex != tabController.index && !tabController.indexIsChanging) {
print('setting state'); // <~~ will print one time now
setState(() {});
}
});
}
edit: you'll also need to dispose the tabController. I updated the code above.
I am having this issue github link. What happens is if a widget uses TickerProviderStateMixin then it gets rebuilt when a page navigation occurs. I have a very complex page and rebuilding the whole page causes a UI jank on page navigation. If I do not rebuild then everything is fine no janks. Is there a workaround for this? It seems to me that this is some sort of an internal flutter bug or unexpected behaviour?
Example:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: PageA(title: 'Flutter Demo Home Page'),
);
}
}
class PageA extends StatefulWidget {
PageA({Key key, this.title}) : super(key: key);
final String title;
#override
_PageAState createState() => _PageAState();
}
class _PageAState extends State<PageA>
with SingleTickerProviderStateMixin {
TabController tabController;
#override
void initState() {
super.initState();
tabController = TabController(length: 2, vsync: this);
}
void toPageB() {
//tabController.animateTo(1);
Navigator.push(context, MaterialPageRoute(builder: (BuildContext context) {
return PageB();
}));
}
#override
Widget build(BuildContext context) {
print("Page A");
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: TabBar(
tabs: [
Text(
"Tab A",
style: Theme.of(context).textTheme.bodyText1,
),
Text(
"Tab B",
style: Theme.of(context).textTheme.bodyText1,
)
],
controller: tabController,
),
),
floatingActionButton: FloatingActionButton(
onPressed: toPageB,
child: Icon(Icons.add),
),
);
}
}
class PageB extends StatelessWidget {
#override
Widget build(BuildContext context) {
print("Page B");
return Scaffold(
appBar: AppBar(
title: Text("Page A"),
),
body: Container(
child: Center(
child: Text("Page A"),
),
));
}
}
#override
// ignore: must_call_super
void didChangeDependencies() {}
just add the code to prevent the rebuild, I dont know the side effect, but this walk around works for my app.
This is the solution I used before.
Change your Page A like
class PageA extends StatefulWidget {
PageA({Key key, this.title}) : super(key: key);
final String title;
#override
_PageAState createState() => _PageAState();
}
class _PageAState extends State<PageA> {
TabController tabController;
// #override
// void initState() {
// super.initState();
// tabController = TabController(length: 2, vsync: this);
// }
void toPageB() {
tabController.animateTo(1);
Navigator.push(context, MaterialPageRoute(builder: (BuildContext context) {
return PageB();
}));
}
#override
Widget build(BuildContext context) {
print("Page A");
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: CustomTabBar(
tabs: [
Text(
"Tab A",
style: Theme.of(context).textTheme.bodyText1,
),
Text(
"Tab B",
style: Theme.of(context).textTheme.bodyText1,
)
],
controller: (controller) {
tabController = controller;
},
),
),
floatingActionButton: FloatingActionButton(
onPressed: toPageB,
child: Icon(Icons.add),
),
);
}
}
And add a new class CustomTabBar
class CustomTabBar extends StatefulWidget {
const CustomTabBar({
this.controller,
this.tabs,
Key? key,
}) : super(key: key);
final Function(TabController)? controller;
final List<Widget>? tabs;
#override
_CustomTabBarState createState() => _CustomTabBarState();
}
class _CustomTabBarState extends State<CustomTabBar>
with SingleTickerProviderStateMixin {
late TabController tabController;
#override
void initState() {
super.initState();
tabController =
TabController(length: widget.tabs?.length ?? 0, vsync: this);
if (widget.controller != null) {
widget.controller!(tabController);
}
}
#override
void dispose() {
tabController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return TabBar(
tabs: widget.tabs ?? [],
controller: tabController,
);
}
}
It should fix the issue that Page A rebuild
Switching between tabs initstate() called multiple times.
i have 4 tabs in my tab barA,B,C and D.
case (1) if i switch in tab like from tab A to B it's working fine.
case (2) but if i'm go to tab A to C then initstate() of tab 'B' called two times
results of case (1)
flutter: A
flutter: B
results of case (2)
flutter: A
flutter: B
flutter: C
flutter: B
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin{
TabController _controller;
void initState() {
super.initState();
_controller = TabController(length: 4, vsync: this);
_controller.addListener(_handleSelected);
}
bool alarm = false;
// Function for handle tap event of tab
void _handleSelected() async {
}
Widget build(BuildContext context) {
return DefaultTabController(
length: 4,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
controller: _controller,
tabs: [
Tab(text: "A"),
Tab(text: "B"),
Tab(text: "C"),
Tab(text: "D"),
],
),
actions: [
Switch(
value: alarm,
onChanged: (value) {
},
activeTrackColor: Color(0xffff6b6b),
activeColor: Color(0xffff0000),
),
],
),
body: TabBarView(
controller: _controller,
children: [
A(),
B(),
C(),
D(),
],
),
),
);
}
}
You can use IndexedStack widget to solve this kind of problem.
In _MyHomePageState use one variable to manage index of selected page;
class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin{
int _selectedPage;
/////
Your code
/////
}
In the body of your scaffold implement IndexedStack
body: IndexedStack(
index:_selectedPage,
children: [
A(),
B(),
C(),
D(),
],
),
Now in _handleSelected () method handle take the latest page index from controller and using setState update the tab bar
void _handleSelected () async {
int index = _controller.page ;// get index from controller (I am not sure about exact parameter name for selected index) ;
setState((){
_selectedPage = index;
});
}
To keep a stateful widget alive (not rebuild or re-render), you can use AutomaticKeepAliveClientMixin. By this way, you can easily decide which widget need to rebuild by changing ``wantKeepAlive'' parameter.
Here is a example for Class A:
class A extends StatefulWidget {
#override
_AState createState() => _AState();
}
class _AState extends State<A> with AutomaticKeepAliveClientMixin{
bool _isLoading;
#override
void initState() {
super.initState();
Future.delayed(Duration(seconds: 3)).then((_){
setState(() {
_isLoading = false;
});
});
}
#override
Widget build(BuildContext context) {
return Center(
child: _isLoading == false ?
Text("A")
: CircularProgressIndicator(),
);
}
#override
bool get wantKeepAlive => true;
}
Let's say I have 2 cards and one is shown on screen at a time. I have a button that replaces the current card with other cards. Now assume that there is some data on card 1 and some data on card 2 and I don't want to destroy the data on each of them or I don't want to rebuild any of them again.
I tried using Stack Widget and overlapping one on top of others with a boolean on the top card. The value of this boolean is reversed by calling setstate when the button is pressed. The issue is as soon as I press the button, the new card rebuilds all over again and then shown or initState is called again, which I don't want. Any Solution?
EDIT: Sample Code:
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var toggleFlag = false;
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(
child: toggleFlag
? CustomWidget(color: Colors.blue)
: CustomWidget(color: Colors.red),
),
floatingActionButton: new FloatingActionButton(
onPressed: _toggleCard,
tooltip: 'Increment',
child: new Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
void _toggleCard() {
setState(() {
toggleFlag = !toggleFlag;
});
}
}
class CustomWidget extends StatefulWidget {
var color;
CustomWidget({this.color});
#override
State<StatefulWidget> createState() {
return new MyState();
}
}
class MyState extends State<CustomWidget> {
#override //I don't want this to be called again and again
Widget build(BuildContext context) {
return new Container(
height: 100.0,
width: 100.0,
color: widget.color,
);
}
}
1-Solution:
You have an array of widgets like this
final widgetList[widget1(), widget2()]
int currentIndex = 0;
IndexedStack (
  index: currentIndex,
  children: widgetList,
 ));
2-Solution:
With the Stack widget
int currentIndex = 0;
Stack(
children: [
Offstage(
offstage: currentIndex != 0,
child: bodyList[0],
),
Offstage(
offstage: currentIndex != 1,
child: bodyList[1],
),
Offstage(
offstage: currentIndex != 2,
child: bodyList[2],
),
],
)
3-Solution:
You need to add this to your stateful widget state
AutomaticKeepAliveClientMixin <Widgetname> like this
class _WidgetState extends State <Widgetname> with AutomaticKeepAliveClientMixin <Widgetname> {
#override
  bool get wantKeepAlive => true;
}
just wrap that Widget inside a Visibility widget then set "maintainSate" to true
Visibility(
visible: toggleFlag,
maintainState: true,
child: const CustomWidget(),
)
Stateless widgets are always considered to be perishable. If you want to preserve state, use a StatefulWidget and a State subclass.