flutter - 卡住构造函数初始值设定项

标签 flutter dart flutter-freezed

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

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

最佳答案

卡住中似乎没有构造函数初始化器
所以作为一种选择,我以这种方式解决了它:

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

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

关于flutter - 卡住构造函数初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69661843/

相关文章:

flutter - 我们应该用 Flutter 不同的导航选项选择哪一个?

flutter : How to hide AlertDialog

dart - 从扩展类访问抽象类属性

android - Flutter - 如何使用包含表单的可扩展面板构建 ListView ?

flutter - 库 'package:splashscreen/splashscreen.dart' 是遗留库,不应导入到空安全库中

flutter - @freezed copyWith 缺少密封类

android-studio - Gradle 在从网络下载工件时抛出错误.. 异常 : Gradle task assembleDebug failed with exit code 1

android - 如何在 flutter Google map 中添加自定义尺寸?