I'm using Freezed
to generate data-class on my flutter project.
I did everything exactly like mentioned in the package readme:
import 'package:freezed_annotation/freezed_annotation.dart';
part 'access_token.freezed.dart';
@freezed
class AccessToken with _$AccessToken {
@JsonSerializable()
const factory AccessToken(
@JsonKey(name: 'access_token') String accessToken,
@JsonKey(name: 'refresh_token') String refreshToken,
) = _AccessToken;
factory AccessToken.fromJson(Map<String, Object?> json) =>
_$AccessTokenFromJson(json);
}
The build completes successfully.
When I run the app I'm getting:
lib/services/models/access_token.freezed.dart:118:7: Error: Method not found: '_$$_AccessTokenFromJson'. _$$AccessTokenFromJson(json); ^^^^^^^^^^^^^^^^^^^^^^^ lib/services/models/access_token.freezed.dart:157:12: Error: The method '$$AccessTokenToJson' isn't defined for the class '$_AccessToken'.
- '_$AccessToken' is from 'package:tenant_app/services/models/access_token.dart' ('lib/services/models/access_token.dart'). Try correcting the name to the name of an existing method, or defining a method named '$$_AccessTokenToJson'. return _$$_AccessTokenToJson(
Why Freezed
didn't generate that function correctly? What am I missing?
You have to add the following part:
part 'access_token.g.dart';
And you don't need the following:
@JsonSerializable()
And make sure you run (using build
or watch
below):
flutter pub run build_runner build --delete-conflicting-outputs
I took your example and successfully generated everything using:
import 'package:freezed_annotation/freezed_annotation.dart';
part 'access_token.freezed.dart';
part 'access_token.g.dart';
@freezed
class AccessToken with _$AccessToken {
const factory AccessToken(
@JsonKey(name: 'access_token') String accessToken,
@JsonKey(name: 'refresh_token') String refreshToken,
) = _AccessToken;
factory AccessToken.fromJson(Map<String, Object?> json) => _$AccessTokenFromJson(json);
}
Using freezed_annotation: ^2.1.0
, freezed: ^2.1.0+1
, build_runner: ^2.2.0,
json_annotation: ^4.6.0
, json_serializable: ^6.3.1
Make sure to check that those are included (according to OP in comment to this answer, packages was missing).
Generated .g.dart file:
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'access_token.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_$_AccessToken _$$_AccessTokenFromJson(Map<String, dynamic> json) =>
_$_AccessToken(
json['access_token'] as String,
json['refresh_token'] as String,
);
Map<String, dynamic> _$$_AccessTokenToJson(_$_AccessToken instance) =>
<String, dynamic>{
'access_token': instance.accessToken,
'refresh_token': instance.refreshToken,
};