skip to Main Content

I am calling a simple function that returns a duration object. However, it is null at times. I want to modify the code so that it can return only a duration object and not duration? object.

  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.

3

Answers


  1. Try this method –

    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));
    
    Login or Signup to reply.
  2. Better solution:

    factory ExecutionModel.fromSnapshot(
          DocumentSnapshot<Map<String, dynamic>> snapshot) {
        final data = snapshot.data()!;
        return ExecutionModel(
            selfRef: snapshot.reference,
            state: TimerState.fromString(data['state']),
            timeAdded: data['duration'] != null ? fromJsonDuration(data['duration']) 
                      : const Duration({your default duration});
            activeTimerRef: data['activeTimerRef'],
            paused: fromJsonDateTime(data['paused'] as Timestamp),
            started: fromJsonDateTime(data['started'] as Timestamp));
    
    Login or Signup to reply.
  3. Try this

    Duration fromJsonDuration(int? milliseconds) {
      if (milliseconds != null) {
        return Duration(milliseconds: milliseconds);
      } else {
        return Duration.zero; // or any other default value.
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search