Skip to content

Allow RestorationAPI to restore any StatefulWidget at runtime #80303

Open

Description

@esDotDev

When switching navigation routes it is often desired to retain various view state such as ScrollPosition, TextFields and Animation state.

Currently this requires using something like an IndexedStack, where all Widgets are kept in the tree and in memory. This is really not conducive to changing routes with Navigator or MaterialApp.router.

It would be nice if somehow we could instead use the StateRestoration API to handle this. Ideally this would be syncronous, and restore data from RAM rather than disk, at least for the most recently cached states.

Desired Result:
When a state is disposed, it saves it's restorable fields. When a state with the same id is loaded again, it fetches any restored state it can. Ideally there is some way we can skip initState() here as well. Or incorporate it into it:

void initState(){
  if(canRestoreState == true) restoreState();
  else {
     // First init
  }
}

Activity

  1. esDotDev commented on Apr 12, 2021

    @esDotDev
    Author

    In terms of use cases, this is widely needed when it comes to app-routing right now, many of the app routing strategies lose state when changing routes with Navigator, and it's cumbersome to implement these basic framework restorations ourselves (restoring our own state is fairly easy, cause we can just hoist that up. But restoring every textField, scroller or AnimationController is a major pain point)

  2. added
    framework
    c: proposal
    a: state restoration
    on Apr 12, 2021
  3. esDotDev commented on Nov 2, 2021

    @esDotDev
    Author

    Any thoughts on this @goderbauer? It seems we're extremely close to being able to do this right now... I just can't figure out how to trigger the Restoration on the state.

    This would really be a game changer when it comes to creating better UX with Flutter and Nav 2.0. Users want their view states to be saved between routes and currently it's very cumbersome. PageStorage works ok, but has a number of limitations/issues. All the plumbing seems to be in place to do this, but I ca't figure out how to make it happen.

    Maybe it's possible already? As a basic example I'd like this view to restore the count each time it loads (the count should persist), but it always resets:

    JqBbr4Aets.mp4
    class App extends StatelessWidget {
      const App({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) => MaterialApp(restorationScopeId: 'app', home: CounterPage());
    }
    
    class CounterPage extends StatefulWidget {
      @override
      State<CounterPage> createState() => _CounterPageState();
    }
    
    class _CounterPageState extends State<CounterPage> with RestorationMixin {
      RestorableInt _count = RestorableInt(0);
    
      @override
      String? get restorationId => 'page1';
    
      @override
      void initState() {
        super.initState();
        // TODO: We need some call here, to tell RestorationManager to give us the latest data.
      }
    
      @override
      void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
        // would like this to fetch the last saved value for this id
        registerForRestoration(_count, 'count');
      }
    
      void _incrementCounter() => setState(() => _count.value++);
     
      // Keep pushing the same page to the navigator, it should be able to persist it's state values
      void _openNewPage() => Navigator.of(context).push<void>(MaterialPageRoute(builder: (_) => CounterPage()));
    
      @override
      Widget build(BuildContext context) => Column(children: [
            OutlinedButton(onPressed: _incrementCounter, child: Text('count=${_count.value}')),
            OutlinedButton(onPressed: _openNewPage, child: Text('Load Page')),
          ]);
    }
  4. HerrNiklasRaab commented on Dec 19, 2021

    @HerrNiklasRaab

    @goderbauer May we have your thought in case this is easy :)

  5. added
    P3
    on May 4, 2022
  6. chunhtai commented on Sep 22, 2022

    @chunhtai
    Contributor

    This may be a memory hazard. Right now restoration only store the current state in memory. so once a statefulwidget is destroyed, the state will be gone. If we enable this, the system need to try to preserve every state that has the restoration mixin without knowing whether it will be reuse in the future.

  7. esDotDev commented on Sep 22, 2022

    @esDotDev
    Author

    There could be a memory limit where the oldest items are purged when a limit is reached? Seems we're usually storing simple primitives here, so in (common) practice it would likely not consume a ton of space?

  8. chunhtai commented on Sep 22, 2022

    @chunhtai
    Contributor

    I think it will be hard to have a default limit or even have this as a default behavior, I think what flutter can do is to provide a hook or an API to customize how state is store and read so that a third party package can decide how it is used.

  9. aytunch commented on Sep 22, 2022

    @aytunch

    We are currently using an IndexedStack and all of our bottom nav bar tabs are always in memory. And our app is video+image intensive. I wish this kind of a solution existed. This would not only help memory pressure, but also battery consumption and general performance as well.

  10. chunhtai commented on Sep 22, 2022

    @chunhtai
    Contributor

    I think of it more, I don't think we need to get thing tangled up with restoration API, we could have a special widget that will prevent subtree to be destroyed and kept it in memory secretly until it was created again. We will still run into the risk about it gets abused and cause the OOM though. This will require change to framework because it currently don't allow dangling Elements or Rendering objects.

  11. aytunch commented on Sep 23, 2022

    @aytunch

    @chunhtai if I understand your strategy correctly, you are talking about a widget similar to Offstage which will not be active at all until enabled? (i.e. no animations and focus will be present in the off state)

  12. chunhtai commented on Sep 23, 2022

    @chunhtai
    Contributor

    No, something like

    PreserveState(
      uniqueTag: ..
      child: TextField
    ),

    what will happen is that once this widget is ever in the widget tree, its state will persist even if it is removed from tree later.

    So you frame 1, you have

    Scaffold(
     body: PreserveState(
      uniqueTag: 'abc',
      child: TextField
    ),
    )

    and they user type something in TextField

    after several frame, tree remove the textfield for some UI change

    Scaffold(
     body: SomeWidget()
    )

    and then after several frames, tree add the textfield back for some UI change

    Scaffold(
     body: PreserveState(
      uniqueTag: 'abc',
      child: TextField
    ),
    )

    it will pick up the old state and fill the user typed text back to TextField

  13. aytunch commented on Sep 23, 2022

    @aytunch

    Thank you for the demonstration. It is very promising.

    child: condition == true ?
      PreserveState(
        uniqueTag: "abc",
        child: TextField()
      ) : Container(),
    

    So even if condition is false and the TextField and the controller attached to it are not in the tree, once condition is back to true, whatever text the user entered will be visible.

    If this was not TextField and instead a VideoPlayer what would the memory implications be?
    When the PreserveState/VideoPlayer is not in the tree, do CPU and RAM is in full usage? Or are they as if there was no video player ever created in terms of resources?

    What will happen behind the scenes of PreserveState?

  14. chunhtai commented on Sep 23, 2022

    @chunhtai
    Contributor

    If we go with AutomaticKeepAlive route, the elements and renderobject will be kept alive, but in reasonable lifecycle state. so in theory, the videoplay if not pause, may still consuming resource, but it really depends on the implementation. This is just one idea I came up, there obvious need more thought on how to make it less dangerous to use.

    Another way would be PreserveState only preserve restorable state, but that will require subtree to opt in to state restoration. This will store less data in memory to mitigate OOM, but it is still possible thing may go out of control.

  15. esDotDev commented on Sep 26, 2022

    @esDotDev
    Author

    I think of it more, I don't think we need to get thing tangled up with restoration API, we could have a special widget that will prevent subtree to be destroyed and kept it in memory secretly until it was created again. We will still run into the risk about it gets abused and cause the OOM though. This will require change to framework because it currently don't allow dangling Elements or Rendering objects.

    This would be a great addition to the SDK, yes it's a little dangerous but it provides so much power and utility. For years I've wished for some other way to keep views in memory other than Offstage widget.

    We would just need some basic API to purge by ID, or purge all memory.

  16. added
    team-framework
    triaged-framework
    on Jul 8, 2023
  17. YukiAttano commented on Jul 21, 2025

    @YukiAttano

    Hi, i am curious about the problem.
    Was this issue fixed in the last years? Because i am using PageStorageKeys in my application and they work.
    I just had to implement a StorageBucket for BottomSheets to get them working too.

    Are their other things around the state restoration?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3a: state restorationc: proposalframeworkteam-frameworktriaged-framework

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions