Skip to content

Freezed + Injectable + OpenApi Generator #82

@alexanderkorus-oskar

Description

@alexanderkorus-oskar

Hi,

I'm using the OpenApi Generator to generate my ApiClient and Backend Models with JSON Serialization and want to Auto Map the backend Model into my Entities, which declared as freezed Models. So my generated Model looks like this:

//
// AUTO-GENERATED FILE, DO NOT MODIFY!
//
// ignore_for_file: unused_element
import 'package:json_annotation/json_annotation.dart';
part 'api_country.g.dart';

@JsonSerializable(
  checked: true,
  createToJson: true,
  disallowUnrecognizedKeys: false,
  explicitToJson: true,
)
class ApiCountry {
  /// Returns a new [ApiCountry] instance.
  ApiCountry({
    required  this.id,
     this.name,
     this.isoCode,
  });

  @JsonKey(
    name: r'id',
    required: true,
    includeIfNull: false
  )
  final int id;

  @JsonKey(
    name: r'name',
    required: false,
    includeIfNull: false
  )
  final String? name;

  @JsonKey(
    name: r'isoCode',
    required: false,
    includeIfNull: false
  )
  final String? isoCode;

  @override
  bool operator ==(Object other) => identical(this, other) || other is ApiCountry &&
     other.id == id &&
     other.name == name &&
     other.isoCode == isoCode;

  @override
  int get hashCode =>
    id.hashCode +
    name.hashCode +
    isoCode.hashCode;

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

  Map<String, dynamic> toJson() => _$ApiCountryToJson(this);

  @override
  String toString() {
    return toJson().toString();
  }
}

and my Freezed Entity like this:

import 'package:freezed_annotation/freezed_annotation.dart';

part 'country.freezed.dart';

@freezed
class Country with _$Country {
  const factory Country({
    required int id,
    String? name,
    String? isoCode
  }) = _Country;
}

Now I want to create a Mapper class like this:

import 'package:domain/domain.dart';
import 'package:injectable/injectable.dart';
import 'package:sample_api_client/sample_api_client.dart';
import 'package:smartstruct/smartstruct.dart';

part 'country_mapper.mapper.g.dart';

@Mapper(useInjection: true) 
abstract class CountryMapper {
  @Mapping(target: "copyWith", ignore: true)
  Country fromModel(ApiCountry model);
}

But on generation I'm getting the Bad state: no element error, like in another thread for freezed. I think this results from not mapping freezed into freezed, so the question is: Will this possible in the future or did I oversee something?

Thanks in advance, maybe I can find a way myself.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions