0

我有这样的模型(简化):

@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';
}

现在我决定迁移到freezed 但不明白如何处理像assetPath

我有很多模型,它们的初始值基于构造函数参数

我的冷冻模型:

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'

如何在此处添加assetPath 字段?

所以在迁移到冻结之前,如果我CountryModel这样创建

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

assetPath值应该是'assets/countries/XX.PNG'

4

2 回答 2

1

我已经使用DefaultassetPath.

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


于 2021-10-21T13:11:45.527 回答
0

似乎冻结中没有构造函数初始化程序,
因此作为一个选项,我以这种方式解决了它:

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

从我的角度来看,这不是最好的解决方案,我更喜欢使用构造函数初始化程序,但这次不是

于 2021-10-28T14:36:42.383 回答