smotastic / smartstruct

Dart Code Generator for generating mapper classes
35 stars 20 forks source link

SmartStruct issue generated with freezed #87

Open namlxcntt opened 1 year ago

namlxcntt commented 1 year ago

Hi. I`m using Smartstruct create mapper from UserResponse -> UserModel

Version

smartstruct: ^1.4.0 smartstruct_generator: ^1.4.0 freezed_annotation: ^2.2.0 freezed: ^2.3.2

UserResponse class

`@freezed class UserResponse with _$UserResponse { const factory UserResponse( {@JsonKey(name: 'id') String? id, @JsonKey(name: 'name') String? name, @JsonKey(name: 'phone') String? phone, @JsonKey(name: 'email') String? email, @JsonKey(name: 'birthday') String? birthday, @JsonKey(name: 'avata') String? avatar, @JsonKey(name: 'status') String? status, @JsonKey(name: 'gender') String? gender}) = _UserResponse;

factory UserResponse.fromJson(Map<String, dynamic> json) => _$UserResponseFromJson(json); } `

UserModel class

@freezed class UserModel with _$UserModel { const factory UserModel( {String? id, String? name, String? phone, String? email, String? birthday, String? avatar, String? status, String? gender}) = _UserModel; }

Finally class Mapper

`part 'user_mapper.mapper.g.dart';

@Mapper() abstract class UserMapper { @Mapping( target: 'copyWith', ignore: true) // drawback as freezed generates a getter for the copyWith, and we have no way of determining that the copyWith shouldn't be mapped without explicitly ignoring it UserModel fromModel(UserResponse model); } `

Build error -> Bad state: No element

I'm looking for help, is there anyone who can help me?

moloti commented 1 year ago

I have the same issue...

moloti commented 1 year ago

Ok here is a fix, try adding a constructor:

class UserResponse with $UserResponse { **const UserResponse.\();**

const factory UserResponse( {@jsonkey(name: 'id') String? id, @jsonkey(name: 'name') String? name, @jsonkey(name: 'phone') String? phone, @jsonkey(name: 'email') String? email, @jsonkey(name: 'birthday') String? birthday, @jsonkey(name: 'avata') String? avatar, @jsonkey(name: 'status') String? status, @jsonkey(name: 'gender') String? gender}) = _UserResponse;

If you do this it should work.

namlxcntt commented 1 year ago

@moloti Oh. Wow .I think it`s work but if handle normal then using freezed does not mean anything