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

I developed the restart_app plugin to restart the whole app natively.


Update:

For anyone who get this exception:

MissingPluginException(No implementation found for method restartApp on channel restart)

Just stop and rebuild the app.


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


So simple package: flutter_restart

dependencies:
flutter_restart: ^0.0.3

to use:

void _restartApp() async {
  FlutterRestart.restartApp();
}

The flutter_phoenix package is based on Rémi Rousselet's answer, making it even simpler.

void main() {
  runApp(
    Phoenix(
      child: App(),
    ),
  );
}

Then when you need to restart the app, just call:

Phoenix.rebirth(context);

Tags:

Flutter