跳转至正文

在 Android 上恢复状态

如何在操作系统终止应用后恢复 Android 应用的状态。

当用户运行移动应用后选择运行另一个应用时,第一个应用会进入后台,或称 被置于后台。操作系统(iOS 与 Android 均如此)可能会终止后台应用以释放内存,并提升前台应用的性能。

当用户再次选择该应用、将其带回前台时,操作系统会重新启动它。但除非你在应用被终止前设置了保存状态的方式,否则状态会丢失,应用会从头开始。用户会失去他们期望的连续性,这显然不理想。(想象在点击 Submit 之前 填写冗长表单时被电话打断。)

那么,如何恢复应用状态,使其看起来与进入后台之前一样?

Flutter 在 services 库中通过 RestorationManager(及相关类)提供解决方案。使用 RestorationManager 时,Flutter 框架会在 状态变化时 将状态数据提供给引擎,以便在操作系统发出即将终止应用的信号时应用已就绪,而应用只有片刻时间准备。

概述

#

只需完成几项任务即可启用状态恢复:

  1. Define a restorationScopeId for classes like CupertinoApp, MaterialApp, or WidgetsApp.

  2. CupertinoAppMaterialAppWidgetsApp 等类定义 restorationScopeId

  3. Define a restorationId for widgets that support it, such as TextField and ScrollView. This automatically enables built-in state restoration for those widgets.

  4. 为支持它的 widget(如 TextFieldScrollView)定义 restorationId。这会自动为这些 widget 启用内置状态恢复。

  5. For custom widgets, you must decide what state you want to restore and hold that state in a RestorableProperty. (The Flutter API provides various subclasses for different data types.) Define those RestorableProperty widgets in a State class that uses the RestorationMixin. Register those widgets with the mixin in a restoreState method.

  6. 对于自定义 widget,你必须决定要恢复哪些状态,并在 RestorableProperty 中保存该状态。(Flutter API 为不同数据类型提供多种子类。)在使用 RestorationMixinState 类中定义这些 RestorableProperty widget。在 restoreState 方法中向 mixin 注册这些 widget。

  7. If you use any Navigator API (like push, pushNamed, and so on) migrate to the API that has "restorable" in the name (restorablePush, restorablePushNamed, and so on) to restore the navigation stack.

  8. 若使用任何 Navigator API(如 pushpushNamed 等),请迁移到名称中包含 restorable 的 API (restorablePushrestorablePushNamed 等)以恢复导航栈。

其他注意事项:

  • Providing a restorationScopeId to MaterialApp, CupertinoApp, or WidgetsApp automatically enables state restoration by injecting a RootRestorationScope. If you need to restore state above the app class, inject a RootRestorationScope manually.

  • MaterialAppCupertinoAppWidgetsApp 提供 restorationScopeId 会通过注入 RootRestorationScope 自动启用状态恢复。若需要在应用类 之上 恢复状态,请手动注入 RootRestorationScope

  • The difference between a restorationId and a restorationScopeId: Widgets that take a restorationScopeId create a new restorationScope (a new RestorationBucket) into which all children store their state. A restorationId means the widget (and its children) store the data in the surrounding bucket.

  • restorationIdrestorationScopeId 的区别: 接受 restorationScopeId 的 widget 会创建新的 restorationScope(新的 RestorationBucket),所有子级在其中保存状态。restorationId 表示该 widget(及其子级)在周围的 bucket 中保存数据。

恢复导航状态

#

若希望应用返回到用户最近查看的特定路由(例如购物车),则还必须为导航实现状态恢复。

若直接使用 Navigator API,请将标准方法迁移为可恢复的方法(名称中包含 restorable)。例如,将 push 替换为 restorablePush

测试状态恢复

#

要测试状态恢复,请将移动设备配置为应用进入后台后不保存状态。要了解如何在 iOS 与 Android 上操作,请参阅 RestorationManager 页面上的测试状态恢复

其他资源

#

有关状态恢复的更多信息,请参阅以下资源。