Skip to content

MODEL classes

Valdio Veliu edited this page Mar 29, 2020 · 2 revisions

FYI: A MODEL represents the objects that encapsulate the data of the application.

To create Models you need to understand the basics of OOP (Object-oriented programming) since Dart is an OOP language.

It's clear that each class is basically a blueprint containing a set of member variables or attributes and each class should at least have a limited number of methods providing some functionality over its parameters. 

What do we need our classes to basically do? Well, at least provide us with a way to access the class properties to get and/or update their values, in short, getters & setters. But, I will skip this part (creating getters & setters) for the sake of having to show less code in the examples of this demo and directly access the properties of the classes.

Except for this, we need our classes to provide an easy way to convert data from JSON and to JSON since we are working with external REST APIs in mind and in the case that the state of the app is persisted to the app's cache using JSON format. We plan to use redux to store and persist data locally on the device so we need each class serializable.

Let's see how a MODEL class looks like:

import 'package:flutter_redux_mvvm/models/Category.dart';
import 'package:flutter_redux_mvvm/models/Tag.dart';
import 'package:json_annotation/json_annotation.dart';

part 'ImageItem.g.dart';

@JsonSerializable()
class ImageItem {
  int id;
  String imageUrl;
  int likes;
  int imageWidth;
  int imageHeight;
  List<Tag> tags;
  Category category;

  ImageItem(this.id, this.imageUrl, this.likes, this.imageWidth, this.imageHeight, this.tags, this.category);

  factory ImageItem.fromJson(Map<String, dynamic> json) => _$ImageItemFromJson(json);

  Map<String, dynamic> toJson() => _$ImageItemToJson(this);
}

It is a basic class at first glance but with some extra "sugar" to it. We are not actually implementing the toJson & fromJson methods as that is too much boilerplate code we have to write every time the class is changed in any way. We are utilizing the helper JSON dependencies to do the hard work for us. json_annotation defines the annotations used by json_serializable to create code for JSON serialization and deserialization. The standards for writing the toJson and fromJson methods are taken from the json_serializable documentation.

After this is created follow the steps to generate serializable models. This will create an extra dart file in the project with the missing methods with the name format ImageItem.g.dart, in case of our example.

You can find the rest of the MODELS used in this app in lib/models/.

Clone this wiki locally