確認環境
$ flutter --version
Flutter 3.3.4 • channel stable • https://github.com/flutter/flutter.git
Framework • revision eb6d86ee27 (3 weeks ago) • 2022-10-04 22:31:45 -0700
Engine • revision c08d7d5efc
Tools • Dart 2.18.2 • DevTools 2.15.0
パッケージをインストール
$ dart pub add freezed_annotation
$ dart pub add --dev build_runner
$ dart pub add --dev freezed
@freezed を用いてクラスを定義
lib/main.dart
import 'package:freezed_annotation/freezed_annotation.dart';
part 'main.freezed.dart';
...
class Human with _$Human {
const factory Human({
required String name,
required int age,
}) = _Human;
}
build
$ dart run build_runner build
lib/main.freezed.dart
が出力されました。
呼び出してみる
lib/main.dart
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'main.freezed.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
Widget build(BuildContext context, WidgetRef ref) {
print(11111);
var h = Human(name: 'human name', age: 30);
print(h);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('My First app'),
),
body: null));
}
}
class Human with _$Human {
const factory Human({
required String name,
required int age,
}) = _Human;
}
デバッグコンソール
I/flutter ( 5588): 11111
I/flutter ( 5588): Human(name: human name, age: 30)