Mixins, Lists And Maps In Flutter 3😜

Introduction

Hi Folks, I hope you’re doing well, In this article, we are discussing mixins and some interesting features in dart language. This is our second series in Object oriented programming in dart. If you directly land on this page I highly recommend please read my previous article. It helps you more understanding about dart oops.

Mixins 😜

Mixins extend the functionality of existing classes and also Mixins are a way of reusing a class code in different class hierarchies. So why use mixin in our code. Please check the below steps for mixin benefits.

  • Encourage Code Reuse in classes 
  • Avoid Inheritance Ambiguity
  • Mixin is also used by interface with implement methods.

Here are some normal codes for BMI calculation. Here I create one class called Person and pass required values like name, age, weight and height. Inside the person class, you will see a method called calculating BMI.

Here I create a new mixin inside a mixin to create a method for calculating our BMI. Once we create mixin extend our person class using the “with” keyword. And call mixin variables and methods as needed.

//Create Mixin
mixin BMI {
    //Create method to calculate our BMI
    double calculateBMI(double weight, double height) {
        return weight / (height * height);
    }
}
void main() {
    final person = Person(name: 'Navinprakash', age: 24, height: 160, weight: 70);
    print(person.bmi);
}
class Person with BMI {
    //Constructor
    Person({
        required this.name,
        required this.age,
        required this.height,
        required this.weight
    });
    final String name;
    final int age;
    final double height;
    final double weight;
    //Computed Properties
    double get bmi => calculateBMI(weight, height);
}

Lists 🀩

Dart List is similar to an array, which is the ordered collection of objects. 

void main() {
    var firstFourPrime = [2, 3, 5, 7];
    firstFourPrime.addAll([11, 13, 17, 19]);
    firstFourPrime.add(23);
    print(firstFourPrime);
}

Here I show you some basic features of lists but the list has a huge number of options. We will discuss the list in future.

Maps

Maps are nothing but a collection of key/value pairs.

void main() {
    var customer = {
        'name': 'Navinprakash',
        'age': 24,
        'address': 'India'
    };
    print(customer['name']);
}

And also this is a simple introduction of lists and maps we will learn clearly in future projects please bear with me.

Conclusion

In this article, we learned about mixins, lists and maps. I explained lists and maps in very basic. I highly recommend please go through for official dart documentation for more about lists and maps. We will cover this topic clearly in future projects as well. In the next article, we will discuss some common concepts in dart. Thank you


Similar Articles