我可以创建和使用简单的 Mixin,但要在 mixin 的方法中访问 setState、mounted、context 等,我需要将它们作为参数从 State 类传递给。
当我使用一些样板代码在 State 上创建 Mixin 以在任何有状态小部件的 State 上使用它时,但我收到两个错误:
error:
The class '_ProfilePageState' cannot implement both 'State<ProfilePage>' and 'State<StatefulWidget>'
because the type arguments are different.
Run Code Online (Sandbox Code Playgroud)
error:
Type parameters could not be inferred for the mixin 'NotificationHandlers'
because no type parameter substitution could be found matching the mixin's supertype constraints.
Run Code Online (Sandbox Code Playgroud)
该mixin定义是这样的:
error:
The class '_ProfilePageState' cannot implement both 'State<ProfilePage>' and 'State<StatefulWidget>'
because the type arguments are different.
Run Code Online (Sandbox Code Playgroud)
cre*_*not 23
你应该这样定义你的mixin:
mixin NotificationHandlers<T extends StatefulWidget> on State<T> {
// Now you can access all of State's members and use the mixin with State classes.
// Example:
@override
void initState() {
// ...
super.initState();
}
}
Run Code Online (Sandbox Code Playgroud)
这确保了泛型类型你的mixin是一样的泛型类型为你的State类。如果省略 for 的类型on State,它将默认为StatefulWidget,但您需要匹配确切的类型,您可以使用我提供的语法进行匹配。
重要的语法是mixin YourMixin<T extends StatefulWidget> on State<T>.
| 归档时间: |
|
| 查看次数: |
2464 次 |
| 最近记录: |