Flutter: how to force an application restart (in p

2019-01-13 23:28发布

问题:

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.

回答1:

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(new RestartWidget(
    child: // new MaterialApp,
  ));
}

class RestartWidget extends StatefulWidget {
  final Widget child;

  RestartWidget({this.child});

  static restartApp(BuildContext context) {
    final _RestartWidgetState state =
        context.ancestorStateOfType(const TypeMatcher<_RestartWidgetState>());
    state.restartApp();
  }

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

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

  void restartApp() {
    this.setState(() {
      key = new UniqueKey();
    });
  }

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

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



回答2:

You can also use the runApp(new MyWidget) function to do something similar

This is what this function does:

Inflate the given widget and attach it to the screen.

The widget is given constraints during layout that force it to fill the entire screen. If you wish to align your widget to one side of the screen (e.g., the top), consider using the Align widget. If you wish to center your widget, you can also use the Center widget

Calling runApp again will detach the previous root widget from the screen and attach the given widget in its place. The new widget tree is compared against the previous widget tree and any differences are applied to the underlying render tree, similar to what happens when a StatefulWidget rebuilds after calling State.setState.

https://docs.flutter.io/flutter/widgets/runApp.html



标签: flutter