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