PencilStroke.fromJson constructor

PencilStroke.fromJson(
  1. Map<String, dynamic> json
)

Implementation

factory PencilStroke.fromJson(Map<String, dynamic> json) {
  assert(() {
    if (json['version'] == null) {
      debugPrint(
        'WARNING: No version information provided. The root cause could be'
        'that you are providing a json that was not created by pencil_field '
        'or the json is corrupted.',
      );
      return true;
    }
    if (json['version'] != 1) {
      debugPrint(
        'WARNING: Only version 1 is supported.',
      );

      // Do not fail, but show the warning
      return true;
    }
    return true;
  }());

  // Make sure there is no crash in production
  if (json['version'] == null) return _emptyStroke();
  if (json['version'] != 1) return _emptyStroke();

  // Decode the points
  final List<dynamic> pointsAsString = json['points'] as List<dynamic>;
  bool pointsSuccessfullyDecoded = true;
  final points = pointsAsString.map((pas) {
    final List<String> xy = pas.split(';');
    double? x;
    double? y;
    try {
      x = double.tryParse(xy[0]);
      y = double.tryParse(xy[1]);
    } catch (e) {
      pointsSuccessfullyDecoded = false;
    }
    if (pointsSuccessfullyDecoded) return Point(x!, y!);
    return const Point(0, 0);
  }).toList();
  assert(() {
    if (pointsSuccessfullyDecoded == false) {
      debugPrint('WARNING: One or more points are not formatted correctly.');
    }
    return true;
  }());
  if (pointsSuccessfullyDecoded == false) return _emptyStroke();

  return PencilStroke(
    points: points,
    bezierDistance:
        json['bezierDistance'] != null ? json['bezierDistance'] as int : 1,
    pencilPaint: PencilPaint.fromJson(json['paint']),
  );
}