📒
Mobile Development Reference-TCE-C01
  • Welcome
  • Introduction
    • Project Description
  • First Steps
    • Creating Project
    • Setting up Workspace
      • Project structure
      • Setting up the app
  • Routing
    • Setting up auto route
    • Creating the first screen
    • Setting up router
    • Adding router to Material App
  • Products Feature
    • Creating models
      • Introduction to freezed
      • Introduction to JSON annotations
      • Creating products model
    • Creating products cubit
      • Creating Products States
      • Creating Products Cubit
      • Implementing Get Products Functionality
    • Creating products repository
      • Setting up Dio
      • Making your first http request with DIO
    • Implementing Products Screen UI
      • Adding Products Grid
      • Adding Products Tile
      • Add Products Error Widget
    • Consuming the products cubit
      • Setting up Dependency injection
      • Creating Bloc Provider for ProductsCubit
      • Mapping Products Cubit states to UI
  • Testing
    • Widget Testing
    • Unit Testing
Powered by GitBook
On this page

Was this helpful?

Export as PDF
  1. Products Feature

Creating models

It is hard to think of a mobile app that doesn’t need to communicate with a web server or easily store structured data at some point. When making network-connected apps, the chances are that it needs to consume some good old JSON, sooner or later.

In case you're not familiar with the term data class, it's simply a class with value equality, copyWith method, its fields are immutable and it usually easily supports serialization. Also, if you're familiar with Kotlin, you know that you can heavily cut down on the boilerplate by defining fields directly in the constructor like this:

KotlinDataClass.kt
data class User(val name: String, val age: Int)

instead of this

DartDataClass.dart
@immutable
class User {
  final String name;
  final int age;

  User(this.name, this.age);

  User copyWith({
    String name,
    int age,
  }) {
    return User(
      name ?? this.name,
      age ?? this.age,
    );
  }

  @override
  bool operator ==(Object o) {
    if (identical(this, o)) return true;

    return o is User && o.name == name && o.age == age;
  }

  @override
  int get hashCode => name.hashCode ^ age.hashCode;
}

instead of coding boilerplate freezed does all this with a few keystrokes

freezed_classes.dart
import 'package:meta/meta.dart';

part 'freezed_classes.freezed.dart';

@immutable
abstract class User with _$User {
  const factory User(String name, int age) = _User;
}

In this section we will be Working on Creating the models of the Products features and the following will be covered.

PreviousAdding router to Material AppNextIntroduction to freezed

Last updated 4 years ago

Was this helpful?

Introduction to Freezed
Introduction to JSON annotation
Creating Products model