Page cover

Motivation

Why do you need Modddels ?

Let's say you want to model a Student object. The Student has a name, an age, and an email. You may create your class/data-class this way :

class Student {
  Student({
    required this.name,
    required this.age,
    required this.email,
  });

  final String name;
  final int age;
  final String email;
}

You will then need to validate the name, age and email in various parts of your app. The Student model will be used in different places : for example, a widget that displays a student profile, or a function addStudent(Student newStudent), etc...

There are several problems with this approach :

  • Where should you validate the name, age and email ?

  • After validation is done, how can you distinguish between a valid Student instance and an invalid one ?

  • How can you ensure that valid Student instances are passed to functions or widgets that require them, and likewise, invalid instances are passed to those that specifically handle them?

  • How to handle an invalid Student differently based on what field is invalid and why it's invalid, all this in various parts of the app ?

  • If you have, for example, a widget that displays the email of a Student. How can you prevent any random string from being passed to the widget ?

All these problems (and more) can be resolved by using this package.

The Modddels package offers a way to validate your models and deal with its different states (valid, invalid...) in a type-safe and compile-safe way.

  • 🔎 Self-Validation : Your models are validated upon creation. This way, you'll never deal with non-validated models.

  • 🧊 Sealed class : Your model is a sealed class, which union-cases are the different states it can be (valid, invalid...). For example, Student would be a sealed class with union-cases ValidStudent and InvalidStudent.

  • 🚨 Failures handling : Your model, when invalid, holds the responsible failure(s), which you can access anytime anywhere.

  • 🔒 Value Equality and Immutability : All models are immutable and override operator == and hashCode for data equality.

  • 🧪 Unit-testing : Easily test your models and the validation logic.

Last updated