Flutter 开发实战

235课时
1K学过
8分

课程评价 (0)

请对课程作出评价:
0/300

学员评价

暂无精选评价
1分钟

05 InheritedWidget-2

img

接着我们看 BuildContext,如上图,BuildContext 其实只是接口, Element 实现了它。InheritedElementElement 的子类,所以每一个 InheritedElement 实例是一个 BuildContext 实例。同时我们日常使用中传递的 BuildContext 也都是一个 Element 。

所以当我们遇到需要共享 State 时,如果逐层传递 state 去实现共享会显示过于麻烦,那么了解了上面的 InheritedWidget 之后呢?

是否将需要共享的 State,都放在一个 InheritedWidget 中,然后在使用的 widget 中直接取用就可以呢?答案是肯定的!所以如下方这类代码:通常如 焦点、主题色、多语言、用户信息 等都属于 App 内的全局共享数据,他们都会通过 BuildContext(InheritedElement) 获取。

///收起键盘
FocusScope.of(context).requestFocus(new FocusNode());

/// 主题色
Theme.of(context).primaryColor

/// 多语言
Localizations.of(context, GSYLocalizations)
 
/// 通过 Redux 获取用户信息
StoreProvider.of(context).userInfo

/// 通过 Redux 获取用户信息
StoreProvider.of(context).userInfo

/// 通过 Scope Model 获取用户信息
ScopedModel.of<UserInfo>(context).userInfo