如何为通用 class State<T extends StatefulWidget> 编写 mixin
How to write a mixin for a generic class State<T extends StatefulWidget>
我需要为 Flutter 的 State<T extends StatefulWidget>
编写一个扩展,这样我就可以在我的所有状态中使用一个函数,比方说 showSnackBar("Hello world", 5)
。
我试着写一个 mixin
mixin BaseState on State<ProfileScreen> {
final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
void showSnackBar(String text) {
setState(() {
scaffoldKey.currentState.showSnackBar(new SnackBar(
content: new Row(
children: <Widget>[
new CircularProgressIndicator(),
new Text(text == null ? " Logging in" : " $text")
],
)));
});
}
void hideSnackBar() {
setState(() {
scaffoldKey.currentState.hideCurrentSnackBar();
});
}
}
如您所见,它现在在 State<ProfileScreen>
上混合使用。这是个问题,因为我只能在 class ProfileScreenState extends State<ProfileScreen>
中使用这个 mixin。如果没有类型符号,我会得到一个错误:
error: The class 'ProfileScreenState' cannot implement both 'State<ProfileScreen>' and 'State<StatefulWidget>' because the type arguments are different. (conflicting_generic_interfaces at [mobile] lib/Screens/profile.dart:17)
error: Type parameters could not be inferred for the mixin 'BaseState' because no type parameter substitution could be found matching the mixin's supertype constraints (mixin_inference_no_possible_substitution at [mobile] lib/Screens/profile.dart:17)
我尝试 Google 很多次,看到了像 这样的问题,但没有成功。
是的,我知道在 Flutter 中组合比继承更受欢迎,但我认为这是我不知道的事情我会用组合来工作,我觉得继承就可以了。
的内容
mixin BaseState<T extends StatefulWidget> on State<T> {
我做了类似的事情;
mixin BaseState{
....
}
效果不错,不知道效果如何。
我需要为 Flutter 的 State<T extends StatefulWidget>
编写一个扩展,这样我就可以在我的所有状态中使用一个函数,比方说 showSnackBar("Hello world", 5)
。
我试着写一个 mixin
mixin BaseState on State<ProfileScreen> {
final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
void showSnackBar(String text) {
setState(() {
scaffoldKey.currentState.showSnackBar(new SnackBar(
content: new Row(
children: <Widget>[
new CircularProgressIndicator(),
new Text(text == null ? " Logging in" : " $text")
],
)));
});
}
void hideSnackBar() {
setState(() {
scaffoldKey.currentState.hideCurrentSnackBar();
});
}
}
如您所见,它现在在 State<ProfileScreen>
上混合使用。这是个问题,因为我只能在 class ProfileScreenState extends State<ProfileScreen>
中使用这个 mixin。如果没有类型符号,我会得到一个错误:
error: The class 'ProfileScreenState' cannot implement both 'State<ProfileScreen>' and 'State<StatefulWidget>' because the type arguments are different. (conflicting_generic_interfaces at [mobile] lib/Screens/profile.dart:17)
error: Type parameters could not be inferred for the mixin 'BaseState' because no type parameter substitution could be found matching the mixin's supertype constraints (mixin_inference_no_possible_substitution at [mobile] lib/Screens/profile.dart:17)
我尝试 Google 很多次,看到了像
是的,我知道在 Flutter 中组合比继承更受欢迎,但我认为这是我不知道的事情我会用组合来工作,我觉得继承就可以了。
mixin BaseState<T extends StatefulWidget> on State<T> {
我做了类似的事情;
mixin BaseState{ .... }
效果不错,不知道效果如何。