如何确保函数始终返回非可空Duration对象且不修改现有类型?
解决方法:确保
timeAdded始终获得非空Duration 针对你遇到的data['duration']偶尔为null,但timeAdded需要非空Duration的问题,有几种可行的处理方式,不用修改timeAdded的类型:
1. 给null值设置默认Duration(推荐)
直接在调用fromJsonDuration时处理null,用??运算符提供默认的毫秒数(比如0,对应Duration.zero):
factory ExecutionModel.fromSnapshot( DocumentSnapshot<Map<String, dynamic>> snapshot) { final data = snapshot.data()!; // 处理duration可能为null的情况,默认用0毫秒 final durationMs = data['duration'] as int? ?? 0; return ExecutionModel( selfRef: snapshot.reference, state: TimerState.fromString(data['state']), timeAdded: fromJsonDuration(durationMs), activeTimerRef: data['activeTimerRef'], paused: fromJsonDateTime(data['paused'] as Timestamp), started: fromJsonDateTime(data['started'] as Timestamp)); }
这样即便data['duration']是null,也会传入0给fromJsonDuration,确保返回非空的Duration对象。
2. 修改fromJsonDuration支持nullable参数
如果希望把null处理逻辑封装到转换函数里,可以修改函数接收int?类型的参数,内部处理null:
Duration fromJsonDuration(int? milliseconds) { // 当参数为null时,默认返回Duration.zero return Duration(milliseconds: milliseconds ?? 0); }
然后调用时直接传入可能为null的data['duration']:
timeAdded: fromJsonDuration(data['duration'] as int?),
3. 异常处理(适合不允许出现null的场景)
如果data['duration']为null属于异常情况(不应该出现),可以直接抛出错误,避免后续逻辑出错:
factory ExecutionModel.fromSnapshot( DocumentSnapshot<Map<String, dynamic>> snapshot) { final data = snapshot.data()!; final durationMs = data['duration'] as int?; if (durationMs == null) { throw ArgumentError('快照中缺少必填的duration字段'); } return ExecutionModel( selfRef: snapshot.reference, state: TimerState.fromString(data['state']), timeAdded: fromJsonDuration(durationMs), activeTimerRef: data['activeTimerRef'], paused: fromJsonDateTime(data['paused'] as Timestamp), started: fromJsonDateTime(data['started'] as Timestamp)); }
注意
原来的代码中data['duration'] as int会在值为null时抛出CastError,所以必须先将其转为int?类型,再处理null情况,才能保证代码安全运行。
内容的提问来源于stack exchange,提问作者M99Coder
相关产品推荐
相关产品推荐

