Updated 28 April 2023
In this blog, we will see how to reload/restart the flutter app. Actually, I have many ways and pub packages to restart the app and found this way to be the best to reload the app using just a few blocks of codes. In my code, I wrap the whole app into a statefulwidget. And when you want to restart the app, rebuild that stateful widget with a child that possesses a different Key
. If you want to use a package then you can use the flutter_phoenix package.
You may also check our Flutter app development page.
Let’s Start the implementation part.
First, I will create a RestartWidget. This class contain the whole app. The UniqueKey always return a unique value which proves the widget a unique id.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
class RestartWidget extends StatefulWidget { RestartWidget({this.child}); final Widget? child; static void restartApp(BuildContext context) { context.findAncestorStateOfType<_RestartWidgetState>()?.restartApp(); } @override State<StatefulWidget> createState() { return _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 ?? Container(), ); } } |
Now we will call the RestartWidget from Main method in the code.
1 2 3 4 5 6 7 |
void main() async{ runApp( RestartWidget( child: MyApp(selectedLanguage) ), ); } |
Now, call restartApp method from anywhere in the code it will restart the application.
1 |
RestartWidget.restartApp(context); |
Note: The above code makes you lose the whole state of your app.
In conclusion, I hope this code will help you better understand Restart/Reload app in a flutter. If you feel any doubt or queries please comment below.
Thanks for the read this blog and if you want to visit my other blogs click here.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
6 comments