0

Is there a better way to do this?

Assignment(
 dueAt: json['due_at'] == null ? 
               null : 
               DateTime.parse(json['due_at']).toLocal()
)

The attribute "dueAt" in Assignment class can be null and i need to parse the string of json['due_at'] to a DateTime, but json['due_at'] can be null too.

Is not really a problem right now but seems noisy and repetitive.

miguelps
  • 142
  • 3
  • 9
  • 3
    There's currently no language construct make that simpler (see https://github.com/dart-lang/language/issues/360). In the meantime, you could write a helper function so that you don't need to evaluate `json['due_at']` multiple times. – jamesdlin Jul 19 '21 at 01:57
  • Thanks @jamesdlin, I think that's the way to go. – miguelps Jul 19 '21 at 23:00

2 Answers2

2

First and foremost, it looks like you're writing JSON serialization code by hand. Your life will be much easier and less bug-prone if you let a library do this instead. json_serializable is very simple and powerful and 100% worth looking into.

However, this pattern is still common outside of json code.

You could also consider writing an extension method for Object? that behaves like the Kotlin standard library's let function (https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/let.html) You can then use Dart's ?. syntax to handle the rest of the logic:

// extension on T rather than Object? to maintain type information
extension Example<T> on T {
  R let<R>(R Function(T) function) => function(this);
}

This just applies a given function to this, which isn't incredibly useful on it's own, but allows the use of ?.:

final DateTime? dueAt = json['due_at']?.let(DateTime.parse); 

If json['due_at'] evaluates to null, the ?. operator short-circuits, and dueAt is set to null. Otherwise, it evaluates to DateTime.parse(json['due_at']).

Or, you could just use package:kt_dart which ports much of the Kotlin standard library to Dart

cameron1024
  • 9,083
  • 2
  • 16
  • 36
1

In this particular case you may want to use tryParse instead of parse. If dueAt is of type DateTime? you can simply call:

Assignment( dueAt: DateTime.tryParse(json['due_at'])?.toLocal() );

Be aware though that tryParse will return null for any invalid date string (be it null or an improperly formatted string). This may or may not be desired behavior depending on your intended use.

Stephen
  • 4,041
  • 22
  • 39
  • Good one. I think i will use this for Datetimes, but for a "global" use case i will write a helper function as @jamesdlin pointed out. Thanks for your response. – miguelps Jul 19 '21 at 23:08