Converting object to an encodable object failed: Instance of 'Offset'

6,291

I would return the JSON explicitly:

return { 'point': {dx: "$point.dx", dy: "$point.dy"}, };
Share:
6,291
snapshot
Author by

snapshot

Updated on December 20, 2022

Comments

  • snapshot
    snapshot 11 months

    I'm trying to send Dart Offset points by encoding it to Json format using 'dart:convert' library. I have gone through the documentation https://api.flutter.dev/flutter/dart-convert/jsonEncode.html.

    The error I'm getting is for serializing the inbuilt classes.

    The following JsonUnsupportedObjectError was thrown while handling a gesture:
    Converting object to an encodable object failed: Instance of 'Offset'
    

    How can i serialize inbuilt class like Offset and Paint class, is this the correct way to send the data to server?

    TestData class contains Offset point and toJson() function

    class TestData {
      TestData(this.point);
      Offset point;
    
      toJson() {
        return{
          'point': point,
        };
      }
    }
    

    Encoder function

    String jsonEncoder() {
        Map testDataMap = this.testDataObj.toJson();
        String jsonStringData = jsonEncode(testDataMap);
        return jsonStringData;
    }
    
    • camillo777
      camillo777 over 3 years
      I would do it explicitly: return{ 'point': {dx: "$point.dx", dy: "$point.dy"}, };
    • snapshot
      snapshot over 3 years
      Thanks. I implemented using this method and it worked.
    • camillo777
      camillo777 about 3 years
      Hello @snapshot, can I post it as the solution?
    • snapshot
      snapshot about 3 years
      Yes @camillo777.