1

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?

Stéphane de Luca
  • 12,745
  • 9
  • 57
  • 95
  • 1
    In general, not really, but in your case you could do: `t.vdate = DateTime.tryParse(json['vdate'] ?? '');` – jamesdlin Feb 21 '22 at 22:22

2 Answers2

0

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());

Full example

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.
Thierry
  • 7,775
  • 2
  • 15
  • 33
0
t.vdate : (json["vDate"] == null || json["vDate"] == 'null')
            ? null
            : DateTime?.tryParse(json["vDate"]),
jmoerdyk
  • 5,544
  • 7
  • 38
  • 49
MD SHAFFAT
  • 59
  • 1
  • 7
  • While this code may solve the question, [including an explanation](https://meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply – jmoerdyk Aug 17 '22 at 18:19