0

I am using Flutter 3 and go_router v10.0.0 to develop a program.

This program uses the bottomNavigationBar(PageA, PageB, PageC), I hope that after these pages are routed back and forth, the pages can still maintain their state. For example, pageA is a ListView, and now a lot of data has been loaded. When I return to pageA from page B or C, pageA is still what I left at that time.

I realized this function by querying the document(https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/stateful_shell_route.dart).

Now I use TabBarView in PageA, and each View is still a page that loads ListView through the network.

The problem now is: I wrote these codes and put them in them, but their state can't be maintained, and they will be reloaded every time I switch TabBarView pages.

How can I solve this problem? I have checked a lot of posts, which are either useless or out of date. If there is a simpler way to deal with it, I can give up using go_router.

AllinProgram
  • 188
  • 4

2 Answers2

1

You can keep the state of the pages using mixin called AutomaticKeepAliveClientMixin:

class HomePage extends StatefulWidget {
  const HomePage({Key? key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  
  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true; //this needs to be true

  @override
  Widget build(BuildContext context) {
    super.build(context);

    return Scaffold();
  }
}

Do this for all Page A, B and C. Once loaded their state will be kept alive. Read this ARTICLE for better example.

Vivek Chib
  • 837
  • 1
  • 2
  • 13
0

Use a PageStorageKey. It will maintain the state

Moony-Stary
  • 451
  • 10