As mentioned at the start of this book, a Mixin is a class that contains methods for use by other classes without it having to be the parent class of those other classes.
So, a Mixin is a class you can use code from without having to inherit from.
It enables developers to piecemeal classes together without having to get involved with inheritance, abstract classes etc.
Mixins & Code GeneratorsMixins are often used to merge generated code into your code. The generator creates abstract classes containing code. Your code then uses
the ‘with’ + the abstract class name to include that code in your class as a mixin.
ExampleIf you use the ‘json_serializable’ package and you invoke the build_runner to build the serialization / deserialization code, some of that generated code resides in an abstract class. Later on, you combine that code into your classes using a mixin.
See Generating Code for Serializing & Deserializing for more information.
Example – ‘mixins’This app draws circles and squares using a CircleWidget and a SquareWidget. They have corresponding CirclePainter and SquarePainter classes that paint onto the canvas with random colors.
The CirclePainter and SquarePainter use the Colorizer class as a mixin to provide random colors.