Flutter应用还原;活动被系统杀死后,如何保存应用状态? [英] Flutter app restoration; how to save the app state when the activity is killed by the system?

查看:67
本文介绍了Flutter应用还原;活动被系统杀死后,如何保存应用状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名Android开发人员,我想切换为Flutter.我喜欢热重装功能,该功能可以缩短开发时间.到目前为止,阻止我切换的唯一一件事是,当活动被杀死时,flutter缺少保存应用程序状态的选项.在本机android中,该选项是免费提供的( onSaveInstanceState(Bundle savedInstanceState)).所以我的问题是,如何在Flutter中实现相同的功能?谢谢.

I'm an android developer and I want to switch to flutter. I love the hot reload feature that allows for faster development time. The only thing that prevents me from switching so far is that flutter lacks the option to save the app state when the activity is killed. In native android the option is provided for free (onSaveInstanceState(Bundle savedInstanceState)). So my question is, how can I implement the same feature in Flutter? Thanks.

推荐答案

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

Beginning with Flutter 1.22 (which is now in stable), you can make use of RestorationMixin. Here's a full example:

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),
        ),
      ),
    );
  }
}


如何测试:

  • 转到设备设置-开发人员选项,然后打开不保留活动.
    • 现在在您的Android设备上运行该应用程序,点击计数器"按钮,然后按主页"按钮以强制Android退出您的应用程序.

    • Now run the app on your Android device, tap the Counters button and hit the home button to force Android to exit your app.

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

    Open the app again and you should see the counter value persist.

    这篇关于Flutter应用还原;活动被系统杀死后,如何保存应用状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆