fromJson static method

FieldHint fromJson(
  1. Object? json
)

The hint json holds, as toJson writes it. A kind this version does not know is read as FieldKind.text, so a document a later editor wrote still opens.

Throws a DocumentFormatException for anything that is not that shape.

Implementation

static FieldHint fromJson(Object? json) {
  if (json is! Map) {
    throw DocumentFormatException('a field hint is a map, not $json');
  }
  final key = json['key'];
  if (key is! String || key.isEmpty) {
    throw DocumentFormatException('a field hint names its "key": $json');
  }
  final kindName = json['kind'];
  if (kindName is! String) {
    throw DocumentFormatException('the field "$key" names no "kind"');
  }
  double? number(String name) => switch (json[name]) {
    null => null,
    final num n when n.isFinite => n.toDouble(),
    final other => throw DocumentFormatException(
      'the field "$key" has "$name" $other, which is not a number',
    ),
  };
  List<String> words(String name) => switch (json[name]) {
    null => const <String>[],
    final List<Object?> list when list.every((Object? e) => e is String) =>
      List<String>.unmodifiable(list.cast<String>()),
    final other => throw DocumentFormatException(
      'the field "$key" has "$name" $other, which is not a list of words',
    ),
  };
  String? word(String name) => switch (json[name]) {
    null => null,
    final String text => text,
    final other => throw DocumentFormatException(
      'the field "$key" has "$name" $other, which is not text',
    ),
  };
  final Unit? unit;
  try {
    unit = json['unit'] == null ? null : Unit.fromJson(json['unit']);
  } on FormatException catch (error) {
    throw DocumentFormatException('the field "$key": ${error.message}');
  }
  return FieldHint(
    key,
    FieldKind.byName(kindName) ?? FieldKind.text,
    label: word('label'),
    help: word('help'),
    min: number('min'),
    max: number('max'),
    step: number('step'),
    unit: unit,
    choices: words('choices'),
    suffixes: words('suffixes'),
    defaultValue: json['default'],
    readOnly: json['readOnly'] == true,
  );
}