0

I have model like this (simplified):

@immutable
class CountryModel {
  final String name;
  final String isoCode;
  final String assetPath;

  const CountryModel({
    required this.name,
    required this.isoCode,
  }) : assetPath = 'assets/countries/$isoCode.PNG';
}

now I decided to migrate to freezed but can't understand how to deal with fields like assetPath

I have a lot of models, whose initial values based on constructor parameters

my freezed model:

part 'country_model.freezed.dart';

@freezed
class CountryModel with _$CountryModel {

  const factory CountryModel({
    required String name,
    required String isoCode,
  }) = _CountryModel;
}

// : assetPath = 'assets/countries/$isoCode.PNG'

how to add assetPath field here?

so before migration to freezed if I create CountryModel like this

CountryModel(name: 'name', isoCode: 'XX');

assetPath value should be 'assets/countries/XX.PNG'

Nagual
  • 1,576
  • 10
  • 17
  • 27

2 Answers2

2

seems like there is no constructor initialisers in freezed
so as an option I solved it in this way:

part 'country_model.freezed.dart';
part 'country_model.g.dart';

@freezed
class CountryModel with _$CountryModel {
  const CountryModel._();

  const factory CountryModel({
    required String name,
    required String isoCode,
  }) = _CountryModel;

  String get assetPath => 'assets/countries/$isoCode.PNG';
}

from my perspective this is not the best solution, I'd prefer to use constructor initialiser but not this time

Nagual
  • 1,576
  • 10
  • 17
  • 27
1

I've used Default value for assetPath.

import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:flutter/foundation.dart';

part 'country_model.freezed.dart';
part 'country_model.g.dart';

@freezed
class CountryModel with _$CountryModel {
   factory CountryModel({
    required String name,
    required String isoCode,
    @Default("assets/countries/\$isoCode.PNG") String assetPath,
  }) = _CountryModel;

  factory CountryModel.fromJson(Map<String, dynamic> json) =>
      _$CountryModelFromJson(json);
}


Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56