Home > OS >  freezed constructor initialisers
freezed constructor initialisers

Time:10-23

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?

CodePudding user response:

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);
}


  • Related