flutterdartmixins

Flutter Force State to have certain Mixin


I have a mixin (MyMixin) that I apply in the state of some widgets like this:

    class MyStfulWidget extends StatefulWidget {
      @override
      _MyStfulWidget State createState() => _MyStfulWidget State();
    }
    
    class _MyStfulWidget State extends State<MyStfulWidget> with MyMixin { ... }

I sometimes need to pass this stateful widgets as a parameter for a method (MyMethod)

    void myMethod(Widget myWidget) { ... }

The problem with the following method is that it accepts every kind of widgets. If I pass a widget that does not have a MyMixin it will not work properly...

Is there any way to force the "myWidget" parameter to be a stateful widget that contains a mixin in its state?

Thanks for the help!


Solution

  • The way I ended up achieving this was to create a new abstract class MyMixinWidget that extends a Stateful Widget, which in turn forces the createState() to return a new abstract class MyMixinState that extends State with MyMixin.

    abstract class MyMixinWidget extends StatefulWidget {
      const MyMixinWidget({Key? key}) : super(key: key);
    
      @override
      MyMixinState createState();
    }
    
    abstract class MyMixinState<T extends MyMixinWidget> extends State<T> with MyMixin {
    }
    

    So it can be implemented like this

    class MyWidget extends MyMixinWidget {
      const MyWidget({Key? key}) : super(key: key);
    
      @override
      MyMixinState<MyWidget> createState() => _MyWidgetState();
    }
    
    class _MyWidgetState extends MyMixinState<MyWidget> {
      @override
      Widget build(BuildContext context) {
        return const Placeholder();
      }
    }