Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I correctly Mixin on State?

Tags:

flutter

dart

I can create and use simple Mixins but to access setState, mounted, context etc in the mixin's methods I need to pass them to from the State class as parameters.

When I to create a Mixin on a State with some boilerplate code to use it on any statefull widget's State, but I get two errors:

error: 
The class '_ProfilePageState' cannot implement both 'State<ProfilePage>' and 'State<StatefulWidget>'
because the type arguments are different.
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.

The mixin definition looks like this:

mixin NotificationHandlers on State {
  void foo(Map bla) {
    //use setState / context / other properties or State here
  }
}
like image 805
The Tahaan Avatar asked Sep 08 '19 09:09

The Tahaan


People also ask

How do you implement mixin?

The simplest way to implement a mixin in JavaScript is to make an object with useful methods, so that we can easily merge them into a prototype of any class.

How do you use mixin in darts?

We make use of the with keyword followed by one or more mixins names. Mixins can be used in two ways, the first case is when we want to make use of class code in such a way that the class doesn't have any constructor and the object of the class is extended. In such a case, we use the with keyword.

How do Mixins work?

Mixins are a language concept that allows a programmer to inject some code into a class. Mixin programming is a style of software development, in which units of functionality are created in a class and then mixed in with other classes. A mixin class acts as the parent class, containing the desired functionality.

How do I add mixin to flutter?

To implement a mixin , create a class that extends Object and declares no constructors. Unless you want your mixin to be usable as a regular class, use the mixin keyword instead of class . In this way, your Car can run , but cannot be ' handleControlled '.


1 Answers

You should define your mixin like this:

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();
  }
}

This ensures that the generic type of your mixin is the same as the generic type for your State class. If you omit the type for on State, it is going to default to StatefulWidget, but you need to match the exact type, which you can with the syntax I provided.


The important syntax is mixin YourMixin<T extends StatefulWidget> on State<T>.

like image 123
creativecreatorormaybenot Avatar answered Oct 11 '22 23:10

creativecreatorormaybenot