Flutter 应用恢复;当活动被系统杀死时如何保存应用程序状态?

Ton*_*Joe 6 android flutter

我是一名 android 开发人员,我想切换到 flutter。我喜欢允许更快开发时间的热重载功能。到目前为止,唯一阻止我切换的是 flutter 缺少在 Activity 被终止时保存应用程序状态的选项。在原生 android 中,该选项是免费提供的 ( onSaveInstanceState(Bundle savedInstanceState))。所以我的问题是,如何在 Flutter 中实现相同的功能?谢谢。

Cop*_*oad 8

从 Flutter 1.22(现在稳定)开始,您可以使用RestorationMixin. 这是一个完整的例子:

void main() {
  runApp(
    RootRestorationScope(
      restorationId: 'root',
      child: MaterialApp(home: HomePage()),
    ),
  );
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with RestorationMixin {
  final RestorableInt _counter = RestorableInt(0);

  @override
  String get restorationId => 'HomePage';

  @override
  void restoreState(RestorationBucket oldBucket, bool initialRestore) {
    registerForRestoration(_counter, 'counter');
  }

  @override
  void dispose() {
    _counter.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          child: Text('${_counter.value}'),
          onPressed: () => setState(() => ++_counter.value),
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

如何测试:

  • 转到您的设备设置 - 开发人员选项并打开Don't keep activities

在此处输入图片说明

  • 现在在您的 Android 设备上运行该应用程序,点击 Counters 按钮并点击主页按钮以强制 Android 退出您的应用程序。

  • 再次打开应用程序,您应该会看到该counter值仍然存在。