如何强制Flutter重建/重新绘制所有小部件? [英] How to force Flutter to rebuild / redraw all widgets?

查看:920
本文介绍了如何强制Flutter重建/重新绘制所有小部件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以强制Flutter重新绘制所有小部件(例如,更改语言环境后)?

Is there a way to force Flutter to redraw all widgets (e.g. after locale change)?

推荐答案

这种使用方式在这种情况下,您拥有孩子可以读取的数据,但又不想将数据显式传递给所有孩子的构造函数参数,通常需要 InheritedWidget 。 Flutter将自动跟踪哪些小部件依赖于数据,并重建树中已更改的部分。有一个 LocaleQuery 股票示例应用

This type of use case, where you have data that children can read but you don't want to explicitly pass the data to the constructor arguments of all your children, usually calls for an InheritedWidget. Flutter will automatically track which widgets depend on the data and rebuild the parts of your tree that have changed. There is a LocaleQuery widget that is designed to handle locale changes, and you can see how it's used in the Stocks example app.

简而言之,这就是股票在做什么:

Briefly, here's what Stocks is doing:


  • 在根小部件(在本例中为 StocksApp )上放置一个回调,以处理区域设置更改。此回调完成一些工作,然后返回 LocaleQueryData
  • 的自定义实例
  • 将此回调注册为 onLocaleChanged MaterialApp 构造函数
  • 的参数
  • 需要语言环境信息的子窗口小部件使用 LocaleQuery。 of(context)

  • 当区域设置更改时,Flutter仅重绘依赖于区域设置数据的小部件。

  • Put a callback on root widget (in this case, StocksApp) for handling locale changes. This callback does some work and then returns a customized instance of LocaleQueryData
  • Register this callback as the onLocaleChanged argument to the MaterialApp constructor
  • Child widgets that need locale information use LocaleQuery.of(context).
  • When the locale changes, Flutter only redraws widgets that have dependencies on the locale data.

如果要跟踪语言环境更改以外的内容,则可以创建自己的扩展了 InheritedWidget ,并将其包含在应用根目录附近的层次结构中。它的父级应该是 StatefulWidget ,其密钥设置为子级可以访问的 GlobalKey StatefulWidget State 应该拥有您要分发的数据,并公开用于调用<$ c的更改方法$ c> setState 。如果子小部件想要更改 State 的数据,则可以使用全局键获取指向 State 的指针。 ( key.currentState )并在其上调用方法。如果他们想读取数据,则可以调用 InheritedWidget 的子类的静态 of(context)方法,然后这将告诉Flutter每当您的 State 调用 setState 时都需要重建这些小部件。

If you want to track something other than locale changes, you can make your own class that extends InheritedWidget, and include it in the hierarchy near the root of your app. Its parent should be a StatefulWidget with key set to a GlobalKey that accessible to the children. The State of the StatefulWidget should own the data you want to distribute and expose methods for changing it that call setState. If child widgets want change the State's data, they can use the global key to get a pointer to the State (key.currentState) and call methods on it. If they want to read the data, they can call the static of(context) method of your subclass of InheritedWidget and that will tell Flutter that these widgets need to rebuilt whenever your State calls setState.

这篇关于如何强制Flutter重建/重新绘制所有小部件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆