Rocio  O'Keefe

Rocio O'Keefe

1623639780

Inheritance with Mixin in Flutter

Let’s build a mixin that records the user send time on a screen in your flutter apps.

What is Inheritance? Let’s assume that there is a functionality that is used on every screen of the app or in a majority of screens of the app, what you will prefer to implement this functionality writing code once or making a method with the required parameters and using that method in every screen by calling it simple. Of course, we would prefer code reusability, that’s called inheritance.

Now, if there is a class that requires more than one class property, it is not possible to extend that class to more than one class. So to avoid such inheritance ambiguity we require mixins. Mixins are really great in dart as they provide us flexibility for code reusability.

mixins_ are normal classes whose method can be used in another class without extending the class. In dart, we can do this by using the keyword _with_._

In this blog, we shall learn how we build a mixin in a flutter that records the time spend on a particular screen. This functionality is very important if we are using analytics in our app to track the user’s behavior.

Why we require a mixin to do this? Let’s say there are 50 screens in an app and we want to implement a timer in every screen then we need to write code for the timer on every screen if we do such a thing then it is not a good practice as we are using the same code in every screen again and again. So we can create a mixin for it.

Create a mixin named **TimerMixin**** .**

mixin TimerMixin {}

We will create two methods startTimer and disposeTimer which will start the timer and stop the timer.

startTimer() {
  Timer.periodic(Duration(seconds: 1), (Timer timer) {
    timerData.clear();
    timerData.add(timer.tick.toInt());
  });
  return timerData;
}

#inheritance #mixin #dart #flutter

Inheritance with Mixin in Flutter