Load JSON date to Dart DateTime

Issue

I have a Rails server that is delivering a MySQL date. My class is set up based upon the AngularDart tutorial. It doesn’t seem to load correctly.

My artist_service. dart method:

  Future<List<Record>> getArtistsRecords(int id) async {
    String url = 'http://catbox.loc/artists/${id.toString()}/records'; // Rails: artists/:id/records
    try {
      HttpRequest response = await HttpRequest.request(
          url, requestHeaders: headers);
      List data = JSON.decode(response.responseText);
      final records = data
          .map((value) => new Record.fromJson(value))
          .toList();
      return records;
    }
    catch (e) {
      throw _handleError(e);
    }
  }

My artist.dart factory method:

  factory Record.fromJson(Map<String, dynamic> record) =>
  new Record(_toInt(record['id']),
      record['title'],
      record['catalog'],
      record['artist_id'],
      record['label_id'],
      record['style_id'],
      record['alternate_catalog'],
      record['recording_date'],
      record['notes'],
      record['penguin'],
      record['category']
  );

The offending element is recording_date, which is declared as DateTime. When I include in html as {{recording_date}} I get 1958-03-09 for example. If I try {{ recording_date | date}} it errors out as an invalid format. I suspect I’m not setting up the DateTime object correctly. Is it possible to do so with the factory method?

Solution

change

record['recording_date'],

to

DateTime.parse(record['recording_date']),

Answered By – Günter Zöchbauer

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.