Force Flutter redraw all widgets

Is there a way to get Flutter to redraw all widgets (for example, after changing the locale)?

+11
source share
4 answers

This type of use case, where you have data that children can read, but you do not want to explicitly pass data into the constructor arguments of all your children, usually calls InheritedWidget . Flutter will automatically track which widgets are data dependent and rebuild the changed parts of your tree. There is a LocaleQuery widget that is designed to handle locale changes, and you can see how it is used in the Sample Stock Application .

In short, this is what the Stocks does:

  • Place a callback to the root widget (in this case, StocksApp ) to handle locale changes. This callback does some work and then returns a custom instance of LocaleQueryData
  • Register this callback as an onLocaleChanged argument to the onLocaleChanged constructor
  • In child widgets that need locale information, use LocaleQuery.of(context) .
  • When changing the locale, Flutter only redraws widgets that are dependent on locale data.

If you want to track something other than locale changes, you can create your own class that extends InheritedWidget and includes it in the hierarchy next to the root of your application. Its parent must be a StatefulWidget with the key set to GlobalKey , accessible to children. State StatefulWidget must own the data that you want to distribute and expose methods to change that call setState . If child widgets want to change State data, they can use the global key to get a pointer to State ( key.currentState ) and call methods on it. If they want to read the data, they can call the static method of(context) your InheritedWidget subclass, and this will tell Flutter that these widgets need to be rebuilt when your State calls setState .

+14
source

Your widget must have a setState () method, each time this method is called, the widget is redrawn.

Documentation: Widget setState ()

+2
source

What might work in your use case, use Navigator to reload the page. I do this when switching between β€œreal” and β€œdemo” in my application. Here is an example:

 Navigator.of(context).push( new MaterialPageRoute( builder: (BuildContext context){ return new SplashPage(); } ) ); 

You can replace the β€œnew SplashPage ()” in the above code with any main widgets (or screen) that you want to reload. This code can be called from anywhere you have access to the BuildContext (which is most places in the user interface).

+1
source

I explain how to create my own AppBuilder widget in this post.

https://hillelcoren.com/2018/08/15/flutter-how-to-rebuild-the-entire-app-to-change-the-theme-or-locale/

You can use the widget by wrapping it with your MaterialApp, for example:

 Widget build(BuildContext context) { return AppBuilder(builder: (context) { return MaterialApp( ... ); }); } 

You can tell the application to recover using:

 AppBuilder.of(context).rebuild(); 
0
source

All Articles