有没有一种方法可以让函数返回不可为空的值,即使它有可能返回一个值?

问题描述 投票:0回答:1

我正在调用一个返回持续时间对象的简单函数。然而,它有时是空的。我想修改代码,使其只能返回持续时间对象而不返回持续时间?对象。

  factory ExecutionModel.fromSnapshot(
      DocumentSnapshot<Map<String, dynamic>> snapshot) {
    final data = snapshot.data()!;
    return ExecutionModel(
        selfRef: snapshot.reference,
        state: TimerState.fromString(data['state']),
        timeAdded: fromJsonDuration(data['duration'] as int), // this line
        activeTimerRef: data['activeTimerRef'],
        paused: fromJsonDateTime(data['paused'] as Timestamp),
        started: fromJsonDateTime(data['started'] as Timestamp));
Duration fromJsonDuration(int milliseconds) {
  return Duration(milliseconds: milliseconds);
}

Here timeAdded argument is a Duration object and not Duration? object. But it can occasionally have null values. What is the fix around for this? I don't want to change timeAdded to Duration? as it can affect other areas.

flutter function
1个回答
0
投票

试试这个方法 -

factory ExecutionModel.fromSnapshot(
      DocumentSnapshot<Map<String, dynamic>> snapshot) {
    final data = snapshot.data()!;
    return ExecutionModel(
        selfRef: snapshot.reference,
        state: TimerState.fromString(data['state']),
        timeAdded: fromJsonDuration(data['duration'] ?? 0),// <== Use this instead it will pass zero to your funcation if  data['duration'] is Null
        activeTimerRef: data['activeTimerRef'],
        paused: fromJsonDateTime(data['paused'] as Timestamp),
        started: fromJsonDateTime(data['started'] as Timestamp));
© www.soinside.com 2019 - 2024. All rights reserved.