0

Hy guys, I'm kinda new to this thing but pls is there any way one could retain the state of a stateful widget instead of rebuilding the widget each time it is called

--Let's say I have a PageView as my home page and its children are all stateful widgets... and on page swipe I want it to build the child in the list once instead of rebuilding on each page-change

--Here's my code,

!!!

return PageView(

onPageChanged: (cardIndex) {},

scrollDirection: Axis.horizontal,

children: <Widget>[

ChatPage(),

UploadPage(),

NotifyPage(),

Settings()

]
);

...thanks

Ramprasath Selvam
  • 3,868
  • 3
  • 25
  • 41

1 Answers1

0

You can use the mixin class called AutomaticKeepAliveClientMixin in your State class and override the wantKeepAlive method and return true.

Example:

class ChatPage extends StatefulWidget{
   @override
  _ChatPageState createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> with
   AutomaticKeepAliveClientMixin<ChatPage> {

 @override
 bool get wantKeepAlive => true;   // <- override this method

  @override
  Widget build(BuildContext context) {
    return ....
  }
}

For more information, you can refer to this article which implements Persistent Tab bars in Flutter https://medium.com/@diegoveloper/flutter-persistent-tab-bars-a26220d322bc

Ayush Bherwani
  • 2,409
  • 1
  • 15
  • 21