1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

freezedのさまざまな書き方

Last updated at Posted at 2023-11-12

通常のエンティティを作成する

import 'package:freezed_annotation/freezed_annotation.dart';

part 'user.freezed.dart';
@freezed
class User with _$User {
  factory User({
    required String firstName,
    required String lastName,
    required int age,
    @Default(false) bool isMarried,// If you want to define defaultCalue
  }) = _User;

    const User._(); // if you want to define some function, you must determine private constructor
    bool get fullName => '$firstName $lastName'
  
}

jsonを扱うエンティティを作成する

import 'package:freezed_annotation/freezed_annotation.dart';

part 'user.freezed.dart';
part 'user.g.dart';

@freezed
class User with _$User {
  factory User({
    required String firstName,
    required String lastName,
    required int age,
  }) = _User;

  factory User.fromJson(Map<String, dynamic> json) =>
  _$UserFromJson(json);
}


Unionクラスを作成する

import 'package:freezed_annotation/freezed_annotation.dart';

part 'user.freezed.dart';
@freezed
class Platform with _$Platform {
  const factory User.woman() = _Woman;
  const factory User.man() = _Man;
  const User._();// Prevent constructing from constructor.
  String get preName => when(man : () => 'Mr.', woman : () => 'Ms.')
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?