I have 2 pages
(Page A and Page B) that you can navigate from and to via a bottom navigation bar
.
I have a special use can where:
Page A : must be "keptAlive
" most of the time, only 1 scenario where it should rebuild
Page B: must be rebuilt
every time we switch to it.
I got these behaviors working but one, the Dynamic
keepAlive
for Page A.
First of all, the code:
Main Page that holds the navigation:
class Example extends StatefulWidget {
@override
_ExampleState createState() => _ExampleState();
}
class _ExampleState extends State<Example> {
int _currentIndex = 0;
PageController? _pageController;
List<Widget> _pages = [];
@override
void initState() {
super.initState();
_currentIndex = 0;
_pages = [PageA(), PageB()];
_pageController = PageController(initialPage: _currentIndex);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('example')),
body: PageView(
controller: _pageController,
physics: NeverScrollableScrollPhysics(),
children: _pages,
),
bottomNavigationBar: AnimatedBottomNavigationBar.builder(
itemCount: _iconList.length,
activeIndex: _currentIndex,
onTap: (index) {
setState(() {
_currentIndex = index;
_pageController!.jumpToPage(index);
});
},
),
);
}
Now this part works fine, in Page B I don't need to do anything special, as by default with PageView, everytime I switch to that Page, it will rebuild.
Now, for Page A, I want that most of the time it DOESN'T rebuild if navigating from Page B
And I achieve this with: AutomaticKeepAliveClientMixin
and wantKeepAlive
:
Page A widget:
class PageA extends StatefulWidget {
@override
_PageAState createState() => _PageAState();
}
class _PageAState extends State<PageA> with AutomaticKeepAliveClientMixin<PageA> {
bool shouldKeepAlive = true;
@override
void initState() {
super.initState();
}
@override
bool get wantKeepAlive => shouldKeepAlive;
@override
Widget build(BuildContext context) {
super.build(context);
/// .....
So this works great, the Page A is not being rebuilt, but I have a special case,
where if in Page A, the user fills a textField
with any value, and then switches to Page B, I want that if the user goes back to Page A, now it has been reset and rebuilt!
I tried different approaches, but I cannot change the value of wantKeepAlive
once Page A has been built for the first time.
I tried using updateKeepAlive()
but it doesn't help, so does someone have an idea, how I can dynamically set wantKeepAlive
on Page A, so that if I navigate to Page B under some special conditions, when coming back to Page A, it might or might not be reset.