我在使用 freezed
转换此类时遇到了一个小问题,因为不可能有一个不是常量的默认值,所以行 DateTime nocache= DateTime.now()
无法转换为 @Default(DateTime.now()) DateTime nocache
这里是完整的代码
import 'package:equatable/equatable.dart';
abstract class DynamicLinkState extends Equatable {
const DynamicLinkState();
@override
List<Object> get props => [];
}
class DynamicLinkInitial extends DynamicLinkState {
@override
String toString() => 'DynamicLinkInitial';
}
class DynamicLinkToNavigate extends DynamicLinkState {
final String path;
final DateTime nocache = DateTime.now();
DynamicLinkToNavigate({this.path});
@override
List<Object> get props => [path, nocache];
@override
String toString() => 'DynamicLinkToNavigate';
}
我最终怎样才能做到这一点?
其他上下文
我在这里使用 nocache
属性,因为 bloc
被优化为不会多次发送相同的事件,但在这种情况下这是一个有效的用例,因为我可能期望用户收到不止一次相同的动态链接。所以我们找到的解决方案是通过传递一个总是变化的 nocache
参数来简单地使这个优化无效。
因此,这个问题的有效解决方案也可能是简单地删除此解决方法,转而采用更可靠的解决方案。
最佳答案
今天早上我遇到了同样的问题。我看不到实现这一目标的直接方法。但是,可能需要采用不同的方法来解决这个问题。
希望您在应用中使用状态管理解决方案。就我而言,它是 RiverPod。因此,我没有让模型直接知道如何为属性生成默认值,而是让我的 RiverPod 状态提供程序在创建模型时生成该值。
所以有了这样的模型......
@freezed class Pix with _$Pix {
const factory Pix({String? id, String? description, String? uri}) = _Pix;
}
...我需要生成 id(在我的例子中是一个 uuid),我有一个 StateNotifier 为我处理
class PixList extends StateNotifier<List<Pix>> {
PixList([List<Pix>? initialPixList]) : super(initialPixList ?? []);
void add(String description, String uri) {
state = [...state,
Pix(
id: _uuid.v4(),
description: description,
uri: uri
)
];
}
}
因为我的状态提供者应该处理对象的创建,所以我有效地将分配初始 id 值的责任委托(delegate)给提供者,而不是模型本身,它仍然很好,很薄
关于flutter - 常量创建的参数必须是常量表达式,同时使用卡住实现模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65013100/