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.

Last updated