我需要为 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)

我尝试了很多谷歌,看到了 these 之类的问题,但没有成功。

是的,我知道在 Flutter 中组合比继承更受欢迎,但我认为这是我不知道我会使用组合进行工作的事情,我觉得继承会没问题。

最佳答案

我想你正在寻找类似 https://github.com/flutter/flutter/blob/3fbd140e77601686acb336cd2af2838d03ba0572/packages/flutter/lib/src/widgets/ticker_provider.dart#L155 的东西

mixin BaseState<T extends StatefulWidget> on State<T> {

关于inheritance - 如何为泛型类 State<T extends StatefulWidget> 编写 mixin,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54618003/

10-12 01:35
查看更多