createAsync static method

Future<JsonSchema> createAsync(
  1. Object? schema, {
  2. SchemaVersion? schemaVersion,
  3. Uri? fetchedFromUri,
  4. RefProvider? refProvider,
  5. List<CustomVocabulary>? customVocabularies,
  6. Map<String, ValidationContext Function(ValidationContext context, String instanceData)> customFormats = const {},
})

Create a schema from a JSON data.

This method is asynchronous to support fetching of sub-JsonSchemas for items, properties, and sub-properties of the root schema.

If you want to create a JsonSchema synchronously, use create. Note that for create remote reference fetching is not supported.

The schema can either be a decoded JSON object (Only Map or bool per the spec), or alternatively, a String may be passed in and JSON decoding will be handled automatically.

Implementation

static Future<JsonSchema> createAsync(
  Object? schema, {
  SchemaVersion? schemaVersion,
  Uri? fetchedFromUri,
  RefProvider? refProvider,
  List<CustomVocabulary>? customVocabularies,
  Map<String, ValidationContext Function(ValidationContext context, String instanceData)> customFormats = const {},
}) {
  // Default to assuming the schema is already a decoded, primitive dart object.
  Object? data = schema;

  /// JSON Schemas must be [bool]s or [Map]s, so if we encounter a [String], we're looking at encoded JSON.
  /// https://json-schema.org/latest/json-schema-core.html#rfc.section.4.3.1
  if (schema is String) {
    try {
      data = json.decode(schema);
    } catch (e) {
      throw ArgumentError('String data provided to createAsync is not valid JSON.');
    }
  }

  /// Set the Schema version before doing anything else, since almost everything depends on it.
  final version = _getSchemaVersion(schemaVersion, data);

  if (data is Map) {
    return JsonSchema._fromRootMap(
      data,
      schemaVersion,
      fetchedFromUri: fetchedFromUri,
      refProvider: refProvider,
      customVocabularies: customVocabularies,
      customFormats: customFormats,
    )._thisCompleter.future;

    // Boolean schemas are only supported in draft 6 and later.
  } else if (data is bool && version >= SchemaVersion.draft6) {
    return JsonSchema._fromRootBool(
      data,
      schemaVersion,
      fetchedFromUri: fetchedFromUri,
      refProvider: refProvider,
      customVocabularies: customVocabularies,
      customFormats: customFormats,
    )._thisCompleter.future;
  }
  throw ArgumentError(
      'Data provided to createAsync is not valid: Data must be, or parse to a Map (or bool in draft6 or later). | $data');
}