freeze 学习过程中遇到的问题记录

2 阅读1分钟

pub.dev/packages/fr… github.com/rrousselGit…

问题1 : 步骤 1 可以解决绝大部分问题

Disabling invalid_annotation_target warning and warning in generates files

If you plan on using Freezed in combination with json_serializable, recent versions of json_serializable and meta may require you to disable the invalid_annotation_target warning.

To do that, you can add the following to the analysis_options.yaml file at the root of your project:

analyzer:
  errors:
    invalid_annotation_target: ignore

问题2

Missing concrete implementations of '_DBFavorite.toJson', 'getter _DBFavorite.backdropPath', 'getter _DBFavorite.favorite', 'getter _DBFavorite.id', and 6 more.
Try implementing the missing methods, or make the class abstract.dartnon_abstract_class_inherits_abstract_member

解决方法在这里: github.com/rrousselGit…

All snippets have already been updated to use either sealed or abstract. And the changelog mentions that this is now needed.

有问题的写法:

import 'package:freezed_annotation/freezed_annotation.dart';

part 'favorite.freezed.dart';
part 'favorite.g.dart';

@freezed
class DBFavorite with _$DBFavorite {
  const factory DBFavorite({
    required int id,
    required int movieId,
    required String backdropPath,
    required String posterPath,
    required bool favorite,
    required double popularity,
    required DateTime releaseDate,
    required String title,
    required String overview,
  }) = _DBFavorite;

  // Add this private constructor
  const DBFavorite._();

  factory DBFavorite.fromJson(Map<String, dynamic> json) => _$DBFavoriteFromJson(json);

}

没有问题的写法(使用 sealed 修饰类)

import 'package:freezed_annotation/freezed_annotation.dart';

part 'favorite.freezed.dart';
part 'favorite.g.dart';

@freezed
sealed class DBFavorite with _$DBFavorite {
  const factory DBFavorite({
    required int id,
    required int movieId,
    required String backdropPath,
    required String posterPath,
    required bool favorite,
    required double popularity,
    required DateTime releaseDate,
    required String title,
    required String overview,
  }) = _DBFavorite;

  // Add this private constructor
  const DBFavorite._();

  factory DBFavorite.fromJson(Map<String, dynamic> json) => _$DBFavoriteFromJson(json);

}