Say I need to write this to assign a nullable DateTime property:
t.vdate = json['vdate'] != null ? DateTime.parse(json['vdate']) : null;
Is there a more compact way to do it?
Say I need to write this to assign a nullable DateTime property:
t.vdate = json['vdate'] != null ? DateTime.parse(json['vdate']) : null;
Is there a more compact way to do it?
A solution could be to use totring()
on your vDate
.
toString()
on Null
returns the string "null"
that will gracefully fail DateTime.tryParse
.
vDate = DateTime.tryParse(jsonData['vDate'].toString());
import 'dart:convert';
import 'package:intl/intl.dart';
const data = '''
{
"data": [
{
"name": "Laurel",
"vDate": "1965-02-23"
},
{
"name": "Hardy"
}
]
}
''';
class Model {
String name;
DateTime? vDate;
Model({required this.name, this.vDate});
Model.fromJson(Map<String, dynamic> jsonData):
name = jsonData['name'],
vDate = DateTime.tryParse(jsonData['vDate'].toString());
@override
toString() => vDate != null
? '$name was born on ${DateFormat('dd of MMMM yyyy').format(vDate!)}'
: 'I don\'t know when $name was born.';
}
void main(List<String> args) {
final friends = jsonDecode(data)['data'].map((jsonData) {
return Model.fromJson(jsonData);
}).toList();
friends.forEach(print);
}
Which prints the following to the console:
Laurel was born on 23 of February 1965
I don't know when Hardy was born.
t.vdate : (json["vDate"] == null || json["vDate"] == 'null')
? null
: DateTime?.tryParse(json["vDate"]),