Flutter:如何强制应用程序重启(在生产模式下)? [英] Flutter: how to force an application restart (in production mode)?

查看:36
本文介绍了Flutter:如何强制应用程序重启(在生产模式下)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

生产模式中,有没有办法强制完全重启应用程序(我不是谈论开发时的热重载!).

实际用例:

  • 在初始化过程中,应用程序检测到没有网络连接.缺乏网络连接可能会阻止正确启动(例如加载外部资源,如 JSON 文件......).

  • 在初始握手期间,需要下载一些重要资源的新版本(某种更新).

在这两个用例中,我希望应用程序能够完全重启,而不必在 ApplicationState 级别构建复杂的逻辑.

非常感谢您的提示.

解决方案

您可以将整个应用程序包装到一个有状态的小部件中.当你想重新启动你的应用程序时,用一个拥有不同 Key 的孩子重建那个 statefulwidget.

这会让你失去应用的整个状态.

import 'package:flutter/material.dart';无效主(){运行应用程序(重启小部件(孩子:MaterialApp(),),);}类 RestartWidget 扩展 StatefulWidget {RestartWidget({this.child});最终的 Widget 子项;静态无效重启应用程序(构建上下文上下文){context.findAncestorStateOfType<_RestartWidgetState>().restartApp();}@覆盖_RestartWidgetState createState() =>_RestartWidgetState();}class _RestartWidgetState 扩展 State<RestartWidget>{Key key = UniqueKey();无效重启应用程序(){设置状态((){键 = 唯一键();});}@覆盖小部件构建(BuildContext 上下文){返回 KeyedSubtree(钥匙:钥匙,孩子:widget.child,);}}

在此示例中,您可以使用 RestartWidget.restartApp(context) 从任何地方重置您的应用.

In production mode, is there a way to force a full restart of the application (I am not talking about a hot reload at development time!).

Practical use cases:

  • At initialization process the application detects that there is no network connection. The lack of network connectivity might have prevented a correct start up (e.g. loading of external resource such as JSON files...).

  • During the initial handshaking, new versions of some important resources need to be downloaded (kind of update).

In both use cases, I would like the application to proceed with a full restart, rather than having to build a complex logic at the ApplicationState level.

Many thanks for your hints.

解决方案

You could wrap your whole app into a statefulwidget. And when you want to restart you app, rebuild that statefulwidget with a child that possess a different Key.

This would make you loose the whole state of your app.

import 'package:flutter/material.dart';

void main() {
  runApp(
    RestartWidget(
      child: MaterialApp(),
    ),
  );
}

class RestartWidget extends StatefulWidget {
  RestartWidget({this.child});

  final Widget child;

  static void restartApp(BuildContext context) {
    context.findAncestorStateOfType<_RestartWidgetState>().restartApp();
  }

  @override
  _RestartWidgetState createState() => _RestartWidgetState();
}

class _RestartWidgetState extends State<RestartWidget> {
  Key key = UniqueKey();

  void restartApp() {
    setState(() {
      key = UniqueKey();
    });
  }

  @override
  Widget build(BuildContext context) {
    return KeyedSubtree(
      key: key,
      child: widget.child,
    );
  }
}

In this example you can reset your app from everywhere using RestartWidget.restartApp(context).

这篇关于Flutter:如何强制应用程序重启(在生产模式下)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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