While using isar with freezed, getting Unsupported type error for copyWith getter method while build runner.
Here is the model class for which the build_runner is failing.
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:isar/isar.dart';
part 'api_response_model.freezed.dart';
part 'api_response_model.g.dart';
@collection
@freezed
class ApiResponseModel with _$ApiResponseModel {
const ApiResponseModel._();
factory ApiResponseModel({
@JsonKey(name: 'data') String? data,
}) = ResponseModel;
Id get id => Isar.autoIncrement;
factory ApiResponseModel.fromJson(Map<String, Object?> json) =>
_$ApiResponseModelFromJson(json);
}
Here is the error thrown while build_runner command.
Unsupported type. Please annotate the property with @ignore.
package:freezed_isar/api_response_model.freezed.dart:28:51
╷
28 │ $ApiResponseModelCopyWith<ApiResponseModel> get copyWith =>
│ ^^^^^^^^
╵
2
Answers
There will be a conflict.
When we create a collection for "isar" then it generates a "g.dart" file and when use fromJson (freezed) it also generate the "g.dart".
An alternate solution:
Use vs code’s extension : dart data class generator
Create your isar collection like this:
Move your cursor on class Name and tap on hint icon (or press ‘cmd + .’) it’ll show options to generate data class:
Then tap on "Generate data class" then it’ll create all the required methods for a data class like toMap(), fromMap(), copyWith(), toJson(), fromJson() etc.
The generated code will show two errors, one in "toMap()" and other in "fromMap(). To solve this, we need to modify the "id" parameter for both methods
Generated methods:
Updated methods:
Now, your data class is generated and it can be used for isar collection and data conversion also.
The type of
copyWith
function generated byfreezed
is not supported byisar
. To ignorecopyWith
, you can use the@collection
annotation of isar like this:@Collection(ignore: {'copyWith'})