Home > Software engineering >  Riverpod mixin for ConsumerState<ConsumerStatefulWidget> and an Action<SomeIntent>
Riverpod mixin for ConsumerState<ConsumerStatefulWidget> and an Action<SomeIntent>

Time:12-24

I have a mixin that I am using on multiple riverpod ConsumerState<ConsumerStatefulWidget> classes and it works great. But now I want to use the same mixin with an Action<SomeIntent> so that I can re-use code instead of duplicating it. The problem seems to be in the way that I'm currently definining the mixin:

mixin QuickFilesMixin<T extends ConsumerStatefulWidget> on ConsumerState<T> {...}

Restricting the mixin to on ConsumerState<T> is the reason I can't also mix it in with the Action which makes sense. But if I try to unrestrict the mixin using something like...

mixin QuickFilesMixin {...}

...then I am able bolt it onto both the ConsumerStatefulWidget and the Action but it breaks because I lose access to ref inside the mixin which is crucial.

Is there a way that I can access ref inside a mixin that can be mixed in with multiple ConsumerStatefulWidgets and also an Action<SomeIntent>?

CodePudding user response:

An alternate solution is to add the properties/methods you need in your mixin, defining them as abstract.

For example if you want your mixin to be applicable on any object with a WidgetRef ref property, you can do:

mixin MyMixin {
  Ref get ref;
}

This enables:

class MyState extends ConsumerState<...> with MyMixin {}

And also allows:

class MyIntent extends Action<SomeIntent> with MyMixin {
  MyIntent(this.ref);
  final WidgetRef ref;
}
  • Related