How to preserve the state of a page

Viewed 89

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.

1 Answers

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

Related