Flutter: Default Tab Bar Controller does not maintain state after swipe

后端 未结 4 1824
北恋
北恋 2021-01-03 09:55

I am writing an application in flutter that has 4 tabbed views, kinda like the stock android phone app or clock app. One of those views hash a floating action button that wh

相关标签:
4条回答
  • 2021-01-03 10:18

    You need to use AutomaticKeepAliveClientMixin over your stateful widget and implement override method called wantKeepAlive

    class MyApp extends StatefulWidget {
    @override
    createState() => new MyAppState();
    }
    

    use AutomaticKeepAliveClientMixin with your class extending state and ov

    class MyAppState extends State<MyApp> with AutomaticKeepAliveClientMixin<MyApp>{
    
    //your existing code.....
    
    @override
    bool get wantKeepAlive => true;   //by default it will be null, change it to true.
    
    //your existing code......
    
    }
    

    on setting wantKeepAlive to true, initState method will run only once, at the time of creation.

    0 讨论(0)
  • 2021-01-03 10:24
    class _RepoInfoState extends State<RepoInfo> with AutomaticKeepAliveClientMixin {
    
      @override
      bool get wantKeepAlive => true; // Note here
    
      @override
      Widget build(BuildContext context) {
        super.build(context); // Note here
    
        return Text('嘿');
      }
    
    }
    
    0 讨论(0)
  • 2021-01-03 10:32

    You need to use PageStorage widget and PageStoageBucket and wrap your page inside a PageStorage widget.

    Please refer to this tutorial for more details:
    Persisting UI State and Building Bottom Navigation Bars in Dart's Flutter Framework

    0 讨论(0)
  • 2021-01-03 10:42

    Variables in Flutter that are created inside a Stateful widget are updated weithin the change of the state. The state changes when you go to another view and then back. So what you can do is to define two variables. A temporary one that is just for the layout and one that is kept a little longer in storage. Pseudo Code:

    var globalVar;
    Stateful Widget...
    var _temp;
    setState({_temp=yourData; globalVar=yourData})
    doSomethingWithYourText(_temp != null ? _temp : globalVar)
    

    While you use the _temp var for all layout updates. The globalVar changes will not be noticable until the State resets (you change to another view).

    So what this does is save your data in two vars and check wether the State was used before. If not it uses the var that was saved earlier.

    0 讨论(0)
提交回复
热议问题