自Flutter 1.12发布以来,我的以下代码:
static MyInheritedWidget of(BuildContext context) {
return context.inheritFromWidgetOfExactType(MyInheritedWidget) as MyInheritedWidget;
}
警告以下内容:
'inheritFromWidgetOfExactType'已被弃用,不应使用。请改用DependOnInheritedWidgetOfExactType。 v1.12.1之后不推荐使用此功能。 尝试用替代品替换不赞成使用的成员。
但是当我尝试更换它时,它不起作用:
static MyInheritedWidget of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType(MyInheritedWidget) as MyInheritedWidget;
}
有人知道该怎么做吗?谢谢!
答案 0 :(得分:17)
API稍有变化。
现在,该方法不再使用Type
作为参数,而是通用的。
之前:
final widget = context.inheritFromWidgetOfExactType(MyInheritedWidget) as MyInheritedWidget;
之后:
final widget = context.dependOnInheritedWidgetOfExactType<MyInheritedWidget>();
请注意,不再需要强制转换
答案 1 :(得分:1)
替换示例:
之前:与InheritFromWidgetOfExactType
static Name of(BuildContext context) {
return context.inheritFromWidgetOfExactType(Name); //here
}
现在dependOnInheritedWidgetOfExactType (推荐)
static Name of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<Name>(); //here
}
<块引用>
现在不再使用 Type
作为参数,该方法是通用的。
简短的 <...>()
而不是 (...)
答案 2 :(得分:0)
此方法的文档注释只应说明该方法已被弃用并指向新方法(无需重复文档注释)。
获取给定类型的最接近的小部件,该部件必须是具体的InheritedWidget
子类的类型,并向该小部件注册此构建上下文,以便在该小部件发生更改时(或该类型的新小部件为引入,或者小部件消失),将重新构建此构建上下文,以便可以从该小部件中获取新值。
现在是
final ValueInherited v = context.dependOnInheritedWidgetOfExactType<ValueInherited>();