18

I was reading a class like:

class SplashScreenState extends State<SplashScreen>
    with SingleTickerProviderStateMixin {
 ...
 ...
}

And I am just wondering what with keyword refers in this context and why do we use it ?

Abdulrahman Falyoun
  • 3,676
  • 3
  • 16
  • 43

1 Answers1

59

I got the answer from here.

I will break it down

The concept i was looking for is called Mixins

So what are mixins ?

Mixins are a way of reusing a class’s code in multiple class hierarchies, In other words when we need a functionality and we cannot implement it in one of a super class , or it does not make sense to do so

If it's a bit hard to understand let's look at following example

We have the following diagram

Classes

As yellow square refers to the ability of walking And blue square ...... as described in the above diagram

We have here a superclass called Animal which has three subclasses (Mammal, Bird, and Fish)

Some animals share common behavior: A cat and a dove can both walk, but the cat cannot fly. These kinds of behavior are orthogonal to this classification, so we cannot implement these behavior in the superclasses. If a class could have more than one superclass, it would be easy, we could create three other classes: Walker, Swimmer, Flyer. After that, we would just have to inherit Dove and Cat from the Walker class. But in Dart, every class (except for Object) has exactly one superclass. Instead of inheriting from the Walker class, we could implement it, as it if was an interface, but we should have to implement the behavior in multiple classes, so it’s not a good solution.

So here comes the use of with

Let's define the walker class

class Walker {
  void walk() {
    print("I'm walking");
  }
}

And to solve the above issue we make use of mixins

class Cat extends Mammal with Walker {}

class Dove extends Bird with Walker, Flyer {}

Now if we call

main(List<String> arguments) {
  Cat cat = Cat();
  Dove dove = Dove();

  // A cat can walk.
  cat.walk();

  // A dove can walk and fly.
  dove.walk();
  dove.fly();

  // A normal cat cannot fly.
  // cat.fly(); // Uncommenting this does not compile.
}

Abdulrahman Falyoun
  • 3,676
  • 3
  • 16
  • 43
  • The rules have changed since Dart3. Making mixins has become stricter. You can see the differences in this stackoverflow reply: https://stackoverflow.com/a/76235195/7442601 – Damien Doumer Aug 10 '23 at 14:40