AutomaticKeepAliveClientMixin : How to prevent rebuilding tabs

Dr_Skele·2023년 1월 27일
0

Flutter

목록 보기
9/19

Flutter provides awesome widgets and Tab related widgets are some of them.
But when you use TabBar and TabBarView, you realize changing tabs rebuilds whole TabBarView everytime. It's very annoying when some data is loaded inside those view. Rebuilding the widget will just resets them everytime, also the scroll position of the listview.

AutomaticKeepAliveClientMixin will be the key for this problem. Implementing this mixin inside the child of TabBarView will preserve its state. Because it's preserving the state, the child must be a stateful widget.

class _WidgetViewState extends State<WidgetView>
    with AutomaticKeepAliveClientMixin {

  @override
  Widget build(BuildContext context) {
    super.build(context); //calling super.build is required by the mixin.
    return SomeWidget();
  }
  
  @override
  bool get wantKeepAlive => true; //override with True.
}

The mixin can be implemented like this and as you can see, it's very simple.

TabBarView(
         children: [
         	WidgetView(),
         ]
    ),

Nothing needs to be done on the TabBarView side.

I think this is much better way to make a UI with tabs. I've tried other ways like Stacking widgets and hiding other widgets with OffStage, but it's much easier to implement using the mixin and I think that's the way the flutter developers intended.

reference : https://api.flutter.dev/flutter/widgets/AutomaticKeepAliveClientMixin-mixin.html

profile
Tireless And Restless Debugging In Source : TARDIS

0개의 댓글