Objective:

After switching TAB, retain the TAB state to avoid repeated calls to initState

Default:

You can see from the figure above that when tab1 is clicked, the corresponding initState method is called. Clicking on the second and third tabs does not trigger the initState method repeatedly (the pages corresponding to the second and third tabs have already been processed).

Add AutomaticKeepAliveClientMixin solution, and implement corresponding method bool get wantKeepAlive = > true; , and the build method implements the parent method super.build(context); Look at the AutomaticKeepAliveClientMixin inside a description:



class UserPageV2 extends StatefulWidget { @override _UserPageV2State createState() => _UserPageV2State(); } class _UserPageV2State extends State<UserPageV2> with AutomaticKeepAliveClientMixin { @override bool get wantKeepAlive = >true;
  @override  void initState() {
    super.initState();
    print('------UserPageV2---------');  
}
  @override  Widget build(BuildContext context) {
    super.build(context);
    return Container(
      alignment: Alignment.center,
      child: Text('I')); }}Copy the code