Flutter: how to force an application restart (in production mode)?

Issue

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.

Solution

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).

Answered By – Rémi Rousselet

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *