3

How to preserve the state of a page in PageView or how to preserve state of widgets when used with BottomNavigationBar etcetera.

final List<Widget> _pages = const [
const Page1(key: Key("Page1"),),
const Page2(key: Key("Page2"),),
];

int _index=0;

 @override
 Widget build(BuildContext context) {
    return Scaffold(
      body: _pages[_index],
      bottomNavigationBar: BottomNavigationBar(
          currentIndex: _index,
          onTap: (index) => setState(() => _index = index),
          items: [
            BottomNavigationBarItem(
              icon: Icon(
                Icons.edit_outlined,
              ),
            ),
            BottomNavigationBarItem(                  
              icon: Icon(
                Icons.edit_outlined,
              ),),               
          ]),
    );

where Page1() and Page2() get Data from internet.

when moving to previous page, it is calling the API again.

balu k
  • 3,515
  • 2
  • 14
  • 29
  • 2
    What do you mean? @YeasinSheikh – balu k Dec 02 '21 at 10:39
  • Does this answer your question? [How to preserve widget states in flutter, when navigating using BottomNavigationBar?](https://stackoverflow.com/questions/49439047/how-to-preserve-widget-states-in-flutter-when-navigating-using-bottomnavigation) – Md. Yeasin Sheikh Dec 02 '21 at 13:06

1 Answers1

1

You can use Indexed Stack to preserve the data on all pages.

Cons

All the pages (childrens) will be built regardless whether the user visits the page or not.

Alternatives

You can use PageStorageKey

Dharman
  • 30,962
  • 25
  • 85
  • 135
Afzal
  • 291
  • 3
  • 5