How to create models in Flutter | Dart? A Beginners Guide

16 Apr 2021 | Saheb Singh How to create models in Flutter | Dart? A Beginners Guide

Models are the core of the data flow in any of the MVC architecture. Well, there is absolutely no hard and fast rule to use models and you can achieve your task without using the models, but, this can give rise to many problems and it can become extremely difficult to manage the data flow in our application. Let's split this discussion into the following points and I'll explain each of them a bit.

  • What are models?
  • Why do we need models for our applications?
  • Named constructors in Dart
  • Model.fromJson and toJson() methods
  • Accessing values from the model

What are models?

In very simpler terms, models are just classes which help us to determine the structure of the data, for eg - API responses. We all know the concept of classes in Object Oriented Programming, similar to that , we can declare the variables, their data types and can write some methods to add some functionality, for eg - return sume of two numbers. So a very simple model would look something like this.

class DemoModel{

//These are the values that this Demo model can store
int number1;
int number2;

//default Constructor
DemoModel(int num1,int num2){
this.number1 = num1;
this.number2 = num2;
};

//We added some functionality to our model
getSum(){
return this.number1 + this.number2;  
}

}

Now you must have noticed that we have one constructor DemoModel() in the above code. The constructor is used to initialise the values inside the model. We will discuss more about it in a bit.

Why do we need models for our application?

This question is pretty obvious to arise right? Why do we need the models if the same work can be achieved without models? Let's look into the following example.

{
  "name": "Saheb Singh",
  "userId" : 1,
  "email": "saheb@example.com"
}

The above implements a very basic User Model. We can serialize this JSON string using the dart:convert library uisng the json.decode() method that takes a string value and returns Map<String,dynamic>. The values then can be accessed in the following manner.

Map<String, dynamic> user = jsonDecode(jsonString);

print('Hi, ${user['name']}!');
print('You are registered with the mail ${user['email']}.');
print('Your unique id is ${user['userId']}.');

Unfortunately, jsonDecode() returns a Map<String, dynamic>, meaning that you do not know the types of the values until runtime. With this approach, you lose most of the statically typed language features: type safety, autocompletion and most importantly, compile-time exceptions. Your code will become instantly more error-prone.

For example, whenever you access the name or email fields, you could quickly introduce a typo. A typo that the compiler doesn’t know about since the JSON lives in a map structure. To combat these problems, Models comes into the play as we strictly define the datatype of the values to be used which makes the code less prone to errors as most the errors can be handled during the compile time which are considerably easy to manage than run-time errors.

Named Constructors in Dart.

Constructors are used to initialise the object of the class. Put in simpler terms, we need to initialise our model with some values which can be achieved using the constructors. Constructors are special methods with the same name as the class name. You might remember the DemoModel() constructor in the example above. Let's look into the following code snipped which initialises our DemoModel object.

//This line of code will initialise num1 as 1 and num2 as 2
DemoModel demoModel = DemoModel(1,2);

fromJson() named constructor

Named constructors are constructors which can be differentiated with names. The syntax to declare a named constructor is ClassName.<constructorName>(). For eg - DemoModel.fromJson(). We will be using this named constructor, fromJson() quite a lot in Flutter as the response that we normally get from APIs are in Json Format(Map in dart). A simple fromJson named constructor will look like this:

//This constructor also does the work of initialising the variables
DemoModel.fromJson(Map<String,dynamic> json){
this.num1 = json['num1'];
this.num2 = json['num2'];
}


//The code to initialise model will look like this
DemoModel model = DemoModel.fromJson(jsonData);

This way we are able to initialise the model values from Json Data. Named constructors makes it possible to have multiple constructors with different ways of initialising the variables.

Accessing values from models.

After initializing the Model, the values can be accessed in the following manner.

DemoModel model = DemoModel(jsonData);
print(model.num1);
print(model.num2);

Complete Model Class

class DemoModel {
  int num1;
  int num2;

  DemoModel({this.num1, this.num2});

  DemoModel.fromJson(Map<String, dynamic> json) {
    num1 = json['num1'];
    num2 = json['num2'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['num1'] = this.num1;
    data['num2'] = this.num2;
    return data;
  }
}

toJson() method will convert the model back into Map format.

Bonus : A perfect tool to make Models easily.

We can create Model classes manually for a simpler data structure easily, but the work becomes more hectic and time consuming if the data we are dealing with is large and complex in nature. We have a perfect tool available just to make our life a lot easier. This tool will take up your JSON data and automatically make Dart Models for you.

Click the below link to open up the tool.

JSON to Dart

That's it for this tutorial. Hope you are able to learn much from this tutorial and are able to understand as why do we need these models in our applications. Feel free to ask any questions or queries on any of my social platforms.

the growing developer
Hi, my name is Saheb Singh , I am a A Software Engineer by Profession. I love to spread the knowledge I gain.I make tutorial videos on Youtube and write blogs for the same.

More blogs related to Flutter

Realtime Database vs Cloud Firestore - Which database to choose ?

Realtime Database vs Cloud Firestore - Which database to choose ? | Flutter

18 Sep 2021 | Saheb Singh

Your Go-to Guide to decide which database to choose and why....

Flutter Tutorial - How to build Beautiful Login Screen with Google Sign - Part I

Flutter Tutorial - How to build Beautiful Login Screen with Google Sign - Part I | Flutter

18 Sep 2021 | Saheb Singh

Let's create a Clean and Materialistic UI Design for Login and see how we can implement google signin using Firebase Auth...

How to fetch data from Internet | Flutter API Integration

How to fetch data from Internet | Flutter API Integration | Flutter

18 Sep 2021 | Saheb Singh

In this video we will learn about fetching data from the Internet. Learn to make API calls from your flutter application...

PageView and PageController | Flutter Tutorial for Beginners

PageView and PageController | Flutter Tutorial for Beginners | Flutter

18 Sep 2021 | Saheb Singh

A complete guide on using PageView and PageController in Flutter....

Using Sqflite in Flutter Application

Using Sqflite in Flutter Application | Flutter

18 Sep 2021 | Saheb Singh

Code explaining the sqflte plugin and how i can perform CRUD operations by creating a local database in our application....

© copyright 2020. All Rights Reserved.