🧊

Flutter のFreezedでFunction型のパラメータの時Null check operator used on a null

2024/01/01に公開

Function型を渡すクラスを作成する必要があり、freezedで作成してみました。

import 'package:freezed_annotation/freezed_annotation.dart';

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


class User with _$User {
  const factory User({
    required String name,
    void Function()? update,
  }) = _User;

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

$ flutter pub run build_runner build

を実行すると、こんなエラーが出ました。

[SEVERE] json_serializable on lib/models/user.dart:

Null check operator used on a null value
[INFO] 14.3s elapsed, 172/179 actions completed.
[INFO] 16.0s elapsed, 175/179 actions completed.
[INFO] Running build completed, took 16.1s

[INFO] Caching finalized dependency graph...
[INFO] Caching finalized dependency graph completed, took 147ms

[SEVERE] Failed after 16.3s
pub finished with exit code 1

json_serializableのところでエラーが出ていて、
Function型のところはJSONでは受け取らないので、@JsonKey(ignore: true)を入れて

import 'package:freezed_annotation/freezed_annotation.dart';

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


class User with _$User {
  const factory User({
    required String name,
    (igore: true) void Function()? update,
  }) = _User;

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

これでエラー解消できました!

Discussion