To programmatically Restart a Flutter app, you can’t directly “restart” the whole app like you would restart an Android/iOS process, but you can simulate a restart by rebuilding the widget tree from the root.
Here’s the most common approach using a custom RestartWidget
:
✅ Step-by-step solution
1. Create a RestartWidget
wrapper
import 'package:flutter/material.dart';
class RestartWidget extends StatefulWidget {
final Widget child;
const RestartWidget({Key? key, required this.child}) : super(key: key);
static void restartApp(BuildContext context) {
final _RestartWidgetState? state =
context.findAncestorStateOfType<_RestartWidgetState>();
state?.restartApp();
}
@override
_RestartWidgetState createState() => _RestartWidgetState();
}
class _RestartWidgetState extends State<RestartWidget> {
Key _key = UniqueKey();
void restartApp() {
setState(() {
_key = UniqueKey(); // Triggers a rebuild with a new key
});
}
@override
Widget build(BuildContext context) {
return KeyedSubtree(
key: _key,
child: widget.child,
);
}
}
2. Wrap your MaterialApp
with RestartWidget
void main() {
runApp(RestartWidget(child: MyApp()));
}
3. Trigger restart when needed
ElevatedButton(
onPressed: () {
RestartWidget.restartApp(context);
},
child: Text("Restart App"),
)
🧠 Important
This will reset the widget tree, but won’t clear static variables, singletons, or caches. If you want a full reset of state, make sure you reset relevant variables too.