diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java index 39e7f784cc94..bba6ad2789df 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java @@ -64,7 +64,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties { public String defaultValue; public String arrayModelType; public boolean isAlias; // Is this effectively an alias of another simple type - public boolean isString, isInteger, isLong, isNumber, isNumeric, isFloat, isDouble, isDate, isDateTime, isShort, isUnboundedInteger, isBoolean; + public boolean isString, isInteger, isLong, isNumber, isNumeric, isFloat, isDouble, isDate, isDateTime, isShort, isUnboundedInteger, isPrimitiveType, isBoolean; private boolean additionalPropertiesIsAnyType; public List vars = new ArrayList<>(); // all properties (without parent's properties) public List allVars = new ArrayList<>(); // all properties (with parent's properties) @@ -637,6 +637,14 @@ public void setIsUnboundedInteger(boolean isUnboundedInteger) { this.isUnboundedInteger = isUnboundedInteger; } + @Override + public boolean getIsPrimitiveType() { return isPrimitiveType; } + + @Override + public void setIsPrimitiveType(boolean isPrimitiveType) { + this.isPrimitiveType = isPrimitiveType; + } + @Override public CodegenProperty getAdditionalProperties() { return additionalProperties; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java index dba1721fbca2..d48b75843af9 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java @@ -623,6 +623,14 @@ public void setIsUnboundedInteger(boolean isUnboundedInteger) { this.isUnboundedInteger = isUnboundedInteger; } + @Override + public boolean getIsPrimitiveType() { return isPrimitiveType; } + + @Override + public void setIsPrimitiveType(boolean isPrimitiveType) { + this.isPrimitiveType = isPrimitiveType; + } + @Override public CodegenProperty getAdditionalProperties() { return additionalProperties; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java index c7a22915dbff..ac78261510f6 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java @@ -536,6 +536,14 @@ public void setIsUnboundedInteger(boolean isUnboundedInteger) { this.isUnboundedInteger = isUnboundedInteger; } + @Override + public boolean getIsPrimitiveType() { return isPrimitiveType; } + + @Override + public void setIsPrimitiveType(boolean isPrimitiveType) { + this.isPrimitiveType = isPrimitiveType; + } + public Map getVendorExtensions() { return vendorExtensions; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java index 7a23b3ab7267..6cc2cd63f90c 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java @@ -371,6 +371,14 @@ public void setIsUnboundedInteger(boolean isUnboundedInteger) { this.isUnboundedInteger = isUnboundedInteger; } + @Override + public boolean getIsPrimitiveType() { return primitiveType; } + + @Override + public void setIsPrimitiveType(boolean isPrimitiveType) { + this.primitiveType = isPrimitiveType; + } + @Override public void setIsModel(boolean isModel) { this.isModel = isModel; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/IJsonSchemaValidationProperties.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/IJsonSchemaValidationProperties.java index eb95821d6f3c..0a4a2d7eec58 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/IJsonSchemaValidationProperties.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/IJsonSchemaValidationProperties.java @@ -95,6 +95,10 @@ public interface IJsonSchemaValidationProperties { void setIsUnboundedInteger(boolean isUnboundedInteger); + boolean getIsPrimitiveType(); + + void setIsPrimitiveType(boolean isPrimitiveType); + CodegenProperty getAdditionalProperties(); void setAdditionalProperties(CodegenProperty additionalProperties); @@ -213,4 +217,4 @@ default void setTypeProperties(Schema p) { setIsAnyType(true); } } -} \ No newline at end of file +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java index 75e466165a55..d8fda925017a 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java @@ -1,5 +1,7 @@ package org.openapitools.codegen.languages; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; import io.swagger.v3.oas.models.Operation; import io.swagger.v3.oas.models.media.ArraySchema; import io.swagger.v3.oas.models.media.Schema; @@ -112,12 +114,13 @@ public AbstractDartCodegen() { setReservedWordsLowerCase(reservedWordsList); // These types return isPrimitive=true in templates - languageSpecificPrimitives = new HashSet<>(5); - languageSpecificPrimitives.add("String"); - languageSpecificPrimitives.add("bool"); - languageSpecificPrimitives.add("int"); - languageSpecificPrimitives.add("num"); - languageSpecificPrimitives.add("double"); + languageSpecificPrimitives = Sets.newHashSet( + "String", + "bool", + "int", + "num", + "double" + ); typeMapping = new HashMap<>(); typeMapping.put("Array", "List"); @@ -148,17 +151,18 @@ public AbstractDartCodegen() { typeMapping.put("AnyType", "Object"); // Data types of the above values which are automatically imported - defaultIncludes = new HashSet<>(); - defaultIncludes.add("String"); - defaultIncludes.add("bool"); - defaultIncludes.add("int"); - defaultIncludes.add("num"); - defaultIncludes.add("double"); - defaultIncludes.add("List"); - defaultIncludes.add("Set"); - defaultIncludes.add("Map"); - defaultIncludes.add("DateTime"); - defaultIncludes.add("Object"); + defaultIncludes = Sets.newHashSet( + "String", + "bool", + "int", + "num", + "double", + "List", + "Set", + "Map", + "DateTime", + "Object" + ); imports.put("String", "dart:core"); imports.put("bool", "dart:core"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java index 25853e0b2541..5693d19265c9 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java @@ -36,6 +36,7 @@ public class DartClientCodegen extends AbstractDartCodegen { public DartClientCodegen() { super(); + final CliOption serializationLibrary = CliOption.newString(CodegenConstants.SERIALIZATION_LIBRARY, "Specify serialization library"); serializationLibrary.setDefault(SERIALIZATION_LIBRARY_NATIVE); diff --git a/modules/openapi-generator/src/main/resources/dart2/README.mustache b/modules/openapi-generator/src/main/resources/dart2/README.mustache index 1b1129159560..ba99ace33f36 100644 --- a/modules/openapi-generator/src/main/resources/dart2/README.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/README.mustache @@ -19,7 +19,7 @@ For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) ## Requirements -Dart 2.0 or later +Dart 2.12 or later ## Installation & Usage diff --git a/modules/openapi-generator/src/main/resources/dart2/api.mustache b/modules/openapi-generator/src/main/resources/dart2/api.mustache index 32f3ee2d8c42..2ce04e81f0eb 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api.mustache @@ -3,7 +3,7 @@ {{#operations}} class {{{classname}}} { - {{{classname}}}([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; + {{{classname}}}([ApiClient? apiClient]) : apiClient = apiClient ?? defaultApiClient; final ApiClient apiClient; {{#operation}} @@ -49,24 +49,13 @@ class {{{classname}}} { /// {{/-last}} {{/allParams}} - Future {{{nickname}}}WithHttpInfo({{#allParams}}{{#required}}{{{dataType}}} {{{paramName}}},{{^-last}} {{/-last}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{ {{#allParams}}{{^required}}{{{dataType}}} {{{paramName}}},{{^-last}} {{/-last}}{{/required}}{{/allParams}} }{{/hasOptionalParams}}) async { - {{#hasParams}} - // Verify required params are set. - {{#allParams}} - {{#required}} - if ({{{paramName}}} == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: {{{paramName}}}'); - } - {{/required}} - {{/allParams}} - - {{/hasParams}} + Future {{{nickname}}}WithHttpInfo({{#allParams}}{{#required}}{{{dataType}}} {{{paramName}}},{{^-last}} {{/-last}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{ {{#allParams}}{{^required}}{{{dataType}}}? {{{paramName}}},{{^-last}} {{/-last}}{{/required}}{{/allParams}} }{{/hasOptionalParams}}) async { // ignore: prefer_const_declarations final path = r'{{{path}}}'{{#pathParams}} .replaceAll({{=<% %>=}}'{<% baseName %>}'<%={{ }}=%>, {{{paramName}}}{{^isString}}.toString(){{/isString}}){{/pathParams}}; // ignore: prefer_final_locals - Object postBody{{#bodyParam}} = {{{paramName}}}{{/bodyParam}}; + Object? postBody{{#bodyParam}} = {{{paramName}}}{{/bodyParam}}; final queryParams = []; final headerParams = {}; @@ -77,7 +66,7 @@ class {{{classname}}} { {{^required}} if ({{{paramName}}} != null) { {{/required}} - queryParams.addAll(_convertParametersForCollectionFormat('{{{collectionFormat}}}', '{{{baseName}}}', {{{paramName}}})); + queryParams.addAll(_queryParams('{{{collectionFormat}}}', '{{{baseName}}}', {{{paramName}}})); {{^required}} } {{/required}} @@ -139,7 +128,7 @@ class {{{classname}}} { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -174,7 +163,7 @@ class {{{classname}}} { /// {{/-last}} {{/allParams}} - Future<{{{returnType}}}{{^returnType}}void{{/returnType}}> {{{nickname}}}({{#allParams}}{{#required}}{{{dataType}}} {{{paramName}}},{{^-last}} {{/-last}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{ {{#allParams}}{{^required}}{{{dataType}}} {{{paramName}}},{{^-last}} {{/-last}}{{/required}}{{/allParams}} }{{/hasOptionalParams}}) async { + Future<{{#returnType}}{{{.}}}?{{/returnType}}{{^returnType}}void{{/returnType}}> {{{nickname}}}({{#allParams}}{{#required}}{{{dataType}}} {{{paramName}}},{{^-last}} {{/-last}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{ {{#allParams}}{{^required}}{{{dataType}}}? {{{paramName}}},{{^-last}} {{/-last}}{{/required}}{{/allParams}} }{{/hasOptionalParams}}) async { final response = await {{{nickname}}}WithHttpInfo({{#allParams}}{{#required}}{{{paramName}}},{{^-last}} {{/-last}}{{/required}}{{/allParams}}{{#hasOptionalParams}} {{#allParams}}{{^required}}{{{paramName}}}: {{{paramName}}},{{^-last}} {{/-last}}{{/required}}{{/allParams}} {{/hasOptionalParams}}); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -183,13 +172,13 @@ class {{{classname}}} { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { {{#native_serialization}} {{#isArray}} final responseBody = await _decodeBodyBytes(response); return (await apiClient.deserializeAsync(responseBody, '{{{returnType}}}') as List) .cast<{{{returnBaseType}}}>() - .{{#uniqueItems}}toSet(){{/uniqueItems}}{{^uniqueItems}}toList(growable: false){{/uniqueItems}}; + .{{#uniqueItems}}toSet(){{/uniqueItems}}{{^uniqueItems}}toList(){{/uniqueItems}}; {{/isArray}} {{^isArray}} {{#isMap}} @@ -199,7 +188,7 @@ class {{{classname}}} { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), '{{{returnType}}}',) as {{{returnType}}}; {{/isMap}}{{/isArray}}{{/native_serialization}} } - return Future<{{{returnType}}}>.value(); + return null; {{/returnType}} } {{/operation}} diff --git a/modules/openapi-generator/src/main/resources/dart2/api_client.mustache b/modules/openapi-generator/src/main/resources/dart2/api_client.mustache index 7eb14870b7ca..92846fc4b910 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_client.mustache @@ -33,12 +33,7 @@ class ApiClient { Client get client => _client; /// Requests to use a new HTTP [Client] in this class. - /// - /// If the [newClient] is null, an [ArgumentError] is thrown. set client(Client newClient) { - if (newClient == null) { - throw ArgumentError('New client instance cannot be null.'); - } _client = newClient; } @@ -55,7 +50,7 @@ class ApiClient { /// or deleted. Map get authentications => Map.unmodifiable(_authentications); - T getAuthentication(String name) { + T? getAuthentication(String name) { final authentication = _authentications[name]; return authentication is T ? authentication : null; } @@ -66,35 +61,28 @@ class ApiClient { String path, String method, List queryParams, - Object body, + Object? body, Map headerParams, Map formParams, - String nullableContentType, + String? contentType, List authNames, ) async { _updateParamsForAuth(authNames, queryParams, headerParams); headerParams.addAll(_defaultHeaderMap); + if (contentType != null) { + headerParams['Content-Type'] = contentType; + } - final urlEncodedQueryParams = queryParams - .where((param) => param.value != null) - .map((param) => '$param'); - - final queryString = urlEncodedQueryParams.isNotEmpty - ? '?${urlEncodedQueryParams.join('&')}' - : ''; - + final urlEncodedQueryParams = queryParams.map((param) => '$param'); + final queryString = urlEncodedQueryParams.isNotEmpty ? '?${urlEncodedQueryParams.join('&')}' : ''; final uri = Uri.parse('$basePath$path$queryString'); - if (nullableContentType != null) { - headerParams['Content-Type'] = nullableContentType; - } - try { // Special case for uploading a single file which isn't a 'multipart/form-data'. if ( - body is MultipartFile && (nullableContentType == null || - !nullableContentType.toLowerCase().startsWith('multipart/form-data')) + body is MultipartFile && (contentType == null || + !contentType.toLowerCase().startsWith('multipart/form-data')) ) { final request = StreamedRequest(method, uri); request.headers.addAll(headerParams); @@ -120,7 +108,7 @@ class ApiClient { return Response.fromStream(response); } - final msgBody = nullableContentType == 'application/x-www-form-urlencoded' + final msgBody = contentType == 'application/x-www-form-urlencoded' ? formParams : await serializeAsync(body); final nullableHeaderParams = headerParams.isEmpty ? null : headerParams; @@ -133,43 +121,71 @@ class ApiClient { case 'HEAD': return await _client.head(uri, headers: nullableHeaderParams,); case 'GET': return await _client.get(uri, headers: nullableHeaderParams,); } - } on SocketException catch (e, trace) { - throw ApiException.withInner(HttpStatus.badRequest, 'Socket operation failed: $method $path', e, trace,); - } on TlsException catch (e, trace) { - throw ApiException.withInner(HttpStatus.badRequest, 'TLS/SSL communication failed: $method $path', e, trace,); - } on IOException catch (e, trace) { - throw ApiException.withInner(HttpStatus.badRequest, 'I/O operation failed: $method $path', e, trace,); - } on ClientException catch (e, trace) { - throw ApiException.withInner(HttpStatus.badRequest, 'HTTP connection failed: $method $path', e, trace,); - } on Exception catch (e, trace) { - throw ApiException.withInner(HttpStatus.badRequest, 'Exception occurred: $method $path', e, trace,); + } on SocketException catch (error, trace) { + throw ApiException.withInner( + HttpStatus.badRequest, + 'Socket operation failed: $method $path', + error, + trace, + ); + } on TlsException catch (error, trace) { + throw ApiException.withInner( + HttpStatus.badRequest, + 'TLS/SSL communication failed: $method $path', + error, + trace, + ); + } on IOException catch (error, trace) { + throw ApiException.withInner( + HttpStatus.badRequest, + 'I/O operation failed: $method $path', + error, + trace, + ); + } on ClientException catch (error, trace) { + throw ApiException.withInner( + HttpStatus.badRequest, + 'HTTP connection failed: $method $path', + error, + trace, + ); + } on Exception catch (error, trace) { + throw ApiException.withInner( + HttpStatus.badRequest, + 'Exception occurred: $method $path', + error, + trace, + ); } - throw ApiException(HttpStatus.badRequest, 'Invalid HTTP operation: $method $path',); + throw ApiException( + HttpStatus.badRequest, + 'Invalid HTTP operation: $method $path', + ); } {{#native_serialization}} - Future deserializeAsync(String json, String targetType, {bool growable}) async => + Future deserializeAsync(String json, String targetType, {bool growable = false,}) async => // ignore: deprecated_member_use_from_same_package deserialize(json, targetType, growable: growable); @Deprecated('Scheduled for removal in OpenAPI Generator 6.x. Use deserializeAsync() instead.') - dynamic deserialize(String json, String targetType, {bool growable}) { + dynamic deserialize(String json, String targetType, {bool growable = false,}) { // Remove all spaces. Necessary for regular expressions as well. targetType = targetType.replaceAll(' ', ''); // ignore: parameter_assignments // If the expected target type is String, nothing to do... return targetType == 'String' ? json - : _deserialize(jsonDecode(json), targetType, growable: growable == true); + : _deserialize(jsonDecode(json), targetType, growable: growable); } {{/native_serialization}} // ignore: deprecated_member_use_from_same_package - Future serializeAsync(Object value) async => serialize(value); + Future serializeAsync(Object? value) async => serialize(value); @Deprecated('Scheduled for removal in OpenAPI Generator 6.x. Use serializeAsync() instead.') - String serialize(Object value) => value == null ? '' : json.encode(value); + String serialize(Object? value) => value == null ? '' : json.encode(value); /// Update query and header parameters based on authentication settings. /// @param authNames The authentications to apply @@ -188,7 +204,7 @@ class ApiClient { } {{#native_serialization}} - static dynamic _deserialize(dynamic value, String targetType, {bool growable}) { + static dynamic _deserialize(dynamic value, String targetType, {bool growable = false}) { try { switch (targetType) { case 'String': @@ -215,24 +231,21 @@ class ApiClient { {{/model}} {{/models}} default: - Match match; - if (value is List && (match = _regList.firstMatch(targetType)) != null) { - targetType = match[1]; // ignore: parameter_assignments + dynamic match; + if (value is List && (match = _regList.firstMatch(targetType)?.group(1)) != null) { return value - .map((dynamic v) => _deserialize(v, targetType, growable: growable)) + .map((dynamic v) => _deserialize(v, match, growable: growable,)) .toList(growable: growable); } - if (value is Set && (match = _regSet.firstMatch(targetType)) != null) { - targetType = match[1]; // ignore: parameter_assignments + if (value is Set && (match = _regSet.firstMatch(targetType)?.group(1)) != null) { return value - .map((dynamic v) => _deserialize(v, targetType, growable: growable)) + .map((dynamic v) => _deserialize(v, match, growable: growable,)) .toSet(); } - if (value is Map && (match = _regMap.firstMatch(targetType)) != null) { - targetType = match[1]; // ignore: parameter_assignments + if (value is Map && (match = _regMap.firstMatch(targetType)?.group(1)) != null) { return Map.fromIterables( value.keys.cast(), - value.values.map((dynamic v) => _deserialize(v, targetType, growable: growable)), + value.values.map((dynamic v) => _deserialize(v, match, growable: growable,)), ); } } @@ -248,9 +261,9 @@ class ApiClient { /// Primarily intended for use in an isolate. class DeserializationMessage { const DeserializationMessage({ - @required this.json, - @required this.targetType, - this.growable, + required this.json, + required this.targetType, + this.growable = false, }); /// The JSON value to deserialize. @@ -274,10 +287,10 @@ Future deserializeAsync(DeserializationMessage message) async { : ApiClient._deserialize( jsonDecode(message.json), targetType, - growable: message.growable == true, + growable: message.growable, ); } {{/native_serialization}} /// Primarily intended for use in an isolate. -Future serializeAsync(Object value) async => value == null ? '' : json.encode(value); +Future serializeAsync(Object? value) async => value == null ? '' : json.encode(value); diff --git a/modules/openapi-generator/src/main/resources/dart2/api_exception.mustache b/modules/openapi-generator/src/main/resources/dart2/api_exception.mustache index 28f734e55879..aeb7aa9ce226 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_exception.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_exception.mustache @@ -6,9 +6,9 @@ class ApiException implements Exception { ApiException.withInner(this.code, this.message, this.innerException, this.stackTrace); int code = 0; - String message; - Exception innerException; - StackTrace stackTrace; + String? message; + Exception? innerException; + StackTrace? stackTrace; @override String toString() { diff --git a/modules/openapi-generator/src/main/resources/dart2/api_helper.mustache b/modules/openapi-generator/src/main/resources/dart2/api_helper.mustache index 6b2f4f2fdef8..ec98b7d1d741 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_helper.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_helper.mustache @@ -11,32 +11,27 @@ class QueryParam { } // Ported from the Java version. -Iterable _convertParametersForCollectionFormat( - String collectionFormat, - String name, - dynamic value, -) { +Iterable _queryParams(String collectionFormat, String name, dynamic value,) { + // Assertions to run in debug mode only. + assert(name.isNotEmpty, 'Parameter cannot be an empty string.'); + final params = []; - // preconditions - if (name != null && name.isNotEmpty && value != null) { - if (value is List) { - if (collectionFormat == 'multi') { - return value.map((dynamic v) => QueryParam(name, parameterToString(v)),); - } + if (value is List) { + if (collectionFormat == 'multi') { + return value.map((dynamic v) => QueryParam(name, parameterToString(v)),); + } - // Default collection format is 'csv'. - if (collectionFormat == null || collectionFormat.isEmpty) { - // ignore: parameter_assignments - collectionFormat = 'csv'; - } + // Default collection format is 'csv'. + if (collectionFormat.isEmpty) { + collectionFormat = 'csv'; // ignore: parameter_assignments + } - final delimiter = _delimiters[collectionFormat] ?? ','; + final delimiter = _delimiters[collectionFormat] ?? ','; - params.add(QueryParam(name, value.map(parameterToString).join(delimiter)),); - } else { - params.add(QueryParam(name, parameterToString(value),)); - } + params.add(QueryParam(name, value.map(parameterToString).join(delimiter),)); + } else if (value != null) { + params.add(QueryParam(name, parameterToString(value))); } return params; @@ -67,27 +62,27 @@ String parameterToString(dynamic value) { Future _decodeBodyBytes(Response response) async { final contentType = response.headers['content-type']; return contentType != null && contentType.toLowerCase().startsWith('application/json') - ? response.bodyBytes == null ? null : utf8.decode(response.bodyBytes) + ? response.bodyBytes.isEmpty ? '' : utf8.decode(response.bodyBytes) : response.body; } /// Returns a valid [T] value found at the specified Map [key], null otherwise. -T mapValueOfType(dynamic map, String key) { +T? mapValueOfType(dynamic map, String key) { final dynamic value = map is Map ? map[key] : null; return value is T ? value : null; } /// Returns a valid Map found at the specified Map [key], null otherwise. -Map mapCastOfType(dynamic map, String key) { +Map? mapCastOfType(dynamic map, String key) { final dynamic value = map is Map ? map[key] : null; return value is Map ? value.cast() : null; } /// Returns a valid [DateTime] found at the specified Map [key], null otherwise. -DateTime mapDateTime(dynamic map, String key, [String pattern]) { +DateTime? mapDateTime(dynamic map, String key, [String? pattern]) { final dynamic value = map is Map ? map[key] : null; if (value != null) { - int millis; + int? millis; if (value is int) { millis = value; } else if (value is String) { diff --git a/modules/openapi-generator/src/main/resources/dart2/api_test.mustache b/modules/openapi-generator/src/main/resources/dart2/api_test.mustache index 319945b2c3b5..6873ba0f9d4d 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_test.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_test.mustache @@ -6,7 +6,7 @@ import 'package:test/test.dart'; /// tests for {{{classname}}} void main() { - final instance = {{{classname}}}(); + // final instance = {{{classname}}}(); group('tests for {{{classname}}}', () { {{#operation}} diff --git a/modules/openapi-generator/src/main/resources/dart2/auth/api_key_auth.mustache b/modules/openapi-generator/src/main/resources/dart2/auth/api_key_auth.mustache index f5d602880de0..b4f5a4587246 100644 --- a/modules/openapi-generator/src/main/resources/dart2/auth/api_key_auth.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/auth/api_key_auth.mustache @@ -6,23 +6,25 @@ class ApiKeyAuth implements Authentication { final String location; final String paramName; - String apiKeyPrefix; - String apiKey; + String apiKeyPrefix = ''; + String apiKey = ''; @override void applyToParams(List queryParams, Map headerParams) { - final value = apiKeyPrefix == null ? apiKey : '$apiKeyPrefix $apiKey'; + final paramValue = apiKeyPrefix.isEmpty ? apiKey : '$apiKeyPrefix $apiKey'; - if (location == 'query' && value != null) { - queryParams.add(QueryParam(paramName, value)); - } else if (location == 'header' && value != null) { - headerParams[paramName] = value; - } else if (location == 'cookie' && value != null) { - headerParams.update( - 'Cookie', - (existingCookie) => '$existingCookie; $paramName=$value', - ifAbsent: () => '$paramName=$value', - ); + if (paramValue.isNotEmpty) { + if (location == 'query') { + queryParams.add(QueryParam(paramName, paramValue)); + } else if (location == 'header') { + headerParams[paramName] = paramValue; + } else if (location == 'cookie') { + headerParams.update( + 'Cookie', + (existingCookie) => '$existingCookie; $paramName=$paramValue', + ifAbsent: () => '$paramName=$paramValue', + ); + } } } } diff --git a/modules/openapi-generator/src/main/resources/dart2/auth/header.mustache b/modules/openapi-generator/src/main/resources/dart2/auth/header.mustache index 341e14bf9e63..3799d9d04658 100644 --- a/modules/openapi-generator/src/main/resources/dart2/auth/header.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/auth/header.mustache @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first diff --git a/modules/openapi-generator/src/main/resources/dart2/auth/http_basic_auth.mustache b/modules/openapi-generator/src/main/resources/dart2/auth/http_basic_auth.mustache index 6098ba5661ea..544219733921 100644 --- a/modules/openapi-generator/src/main/resources/dart2/auth/http_basic_auth.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/auth/http_basic_auth.mustache @@ -1,12 +1,16 @@ {{>header}} {{>part_of}} class HttpBasicAuth implements Authentication { + HttpBasicAuth({this.username = '', this.password = ''}); + String username; String password; @override void applyToParams(List queryParams, Map headerParams) { - final credentials = '${username ?? ''}:${password ?? ''}'; - headerParams['Authorization'] = 'Basic ${base64.encode(utf8.encode(credentials))}'; + if (username.isNotEmpty && password.isNotEmpty) { + final credentials = '$username:$password'; + headerParams['Authorization'] = 'Basic ${base64.encode(utf8.encode(credentials))}'; + } } } diff --git a/modules/openapi-generator/src/main/resources/dart2/auth/http_bearer_auth.mustache b/modules/openapi-generator/src/main/resources/dart2/auth/http_bearer_auth.mustache index 1260ff9c99d0..7c480c5e81d3 100644 --- a/modules/openapi-generator/src/main/resources/dart2/auth/http_bearer_auth.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/auth/http_bearer_auth.mustache @@ -11,19 +11,29 @@ class HttpBearerAuth implements Authentication { set accessToken(dynamic accessToken) { if (accessToken is! String && accessToken is! HttpBearerAuthProvider) { - throw ArgumentError('Type of Bearer accessToken should be a String or a String Function().'); + throw ArgumentError('accessToken value must be either a String or a String Function().'); } _accessToken = accessToken; } @override void applyToParams(List queryParams, Map headerParams) { + if (_accessToken == null) { + return; + } + + String accessToken; + if (_accessToken is String) { - headerParams['Authorization'] = 'Bearer $_accessToken'; + accessToken = _accessToken; } else if (_accessToken is HttpBearerAuthProvider) { - headerParams['Authorization'] = 'Bearer ${_accessToken()}'; + accessToken = _accessToken!(); } else { - throw ArgumentError('Type of Bearer accessToken should be a String or a String Function().'); + return; + } + + if (accessToken.isNotEmpty) { + headerParams['Authorization'] = 'Bearer $accessToken'; } } } diff --git a/modules/openapi-generator/src/main/resources/dart2/auth/oauth.mustache b/modules/openapi-generator/src/main/resources/dart2/auth/oauth.mustache index 6cdd30dceb27..c5c64d522184 100644 --- a/modules/openapi-generator/src/main/resources/dart2/auth/oauth.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/auth/oauth.mustache @@ -1,13 +1,13 @@ {{>header}} {{>part_of}} class OAuth implements Authentication { - OAuth({this.accessToken}); + OAuth({this.accessToken = ''}); String accessToken; @override void applyToParams(List queryParams, Map headerParams) { - if (accessToken != null) { + if (accessToken.isNotEmpty) { headerParams['Authorization'] = 'Bearer $accessToken'; } } diff --git a/modules/openapi-generator/src/main/resources/dart2/dart_constructor.mustache b/modules/openapi-generator/src/main/resources/dart2/dart_constructor.mustache index af2f2a0e2859..dc5dfec5f2a7 100644 --- a/modules/openapi-generator/src/main/resources/dart2/dart_constructor.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/dart_constructor.mustache @@ -2,9 +2,9 @@ {{{classname}}}({ {{#vars}} {{! - A field is @required in Dart when it is - required && !nullable && !defaultValue in OAS + A field is required in Dart when it is + required && !defaultValue in OAS }} - {{#required}}{{^isNullable}}{{^defaultValue}}@required {{/defaultValue}}{{/isNullable}}{{/required}}this.{{{name}}}{{^isNullable}}{{#defaultValue}} = {{#isEnum}}{{^isContainer}}const {{{enumName}}}._({{/isContainer}}{{/isEnum}}{{{defaultValue}}}{{#isEnum}}{{^isContainer}}){{/isContainer}}{{/isEnum}}{{/defaultValue}}{{/isNullable}}, + {{#required}}{{^defaultValue}}required {{/defaultValue}}{{/required}}this.{{{name}}}{{#defaultValue}} = {{#isEnum}}{{^isContainer}}const {{{enumName}}}._({{/isContainer}}{{/isEnum}}{{{.}}}{{#isEnum}}{{^isContainer}}){{/isContainer}}{{/isEnum}}{{/defaultValue}}, {{/vars}} - }); \ No newline at end of file + }); diff --git a/modules/openapi-generator/src/main/resources/dart2/gitignore.mustache b/modules/openapi-generator/src/main/resources/dart2/gitignore.mustache index 8b7331fd822c..1be28ced0940 100644 --- a/modules/openapi-generator/src/main/resources/dart2/gitignore.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/gitignore.mustache @@ -1,27 +1,17 @@ -# See https://www.dartlang.org/tools/private-files.html +# See https://dart.dev/guides/libraries/private-files -# Files and directories created by pub -.buildlog +.dart_tool/ .packages -.project -.pub/ build/ -**/packages/ +pubspec.lock # Except for application packages -# Files created by dart2js -# (Most Dart developers will use pub build to compile Dart, use/modify these -# rules if you intend to use dart2js directly -# Convention is to use extension '.dart.js' for Dart compiled to Javascript to -# differentiate from explicit Javascript files) -*.dart.js -*.part.js -*.js.deps -*.js.map -*.info.json - -# Directory created by dartdoc doc/api/ -# Don't commit pubspec lock file -# (Library packages only! Remove pattern if developing an application package) -pubspec.lock +# IntelliJ +*.iml +*.ipr +*.iws +.idea/ + +# Mac +.DS_Store diff --git a/modules/openapi-generator/src/main/resources/dart2/header.mustache b/modules/openapi-generator/src/main/resources/dart2/header.mustache index 341e14bf9e63..3799d9d04658 100644 --- a/modules/openapi-generator/src/main/resources/dart2/header.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/header.mustache @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first diff --git a/modules/openapi-generator/src/main/resources/dart2/model_test.mustache b/modules/openapi-generator/src/main/resources/dart2/model_test.mustache index 5d4f1c161c52..1a074d47b71d 100644 --- a/modules/openapi-generator/src/main/resources/dart2/model_test.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/model_test.mustache @@ -7,7 +7,7 @@ import 'package:test/test.dart'; // tests for {{{classname}}} void main() { {{^isEnum}} - final instance = {{{classname}}}(); + // final instance = {{{classname}}}(); {{/isEnum}} group('test {{{classname}}}', () { diff --git a/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_class.mustache b/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_class.mustache index 0efe1455c4b5..e6a680201fe7 100644 --- a/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_class.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_class.mustache @@ -1,21 +1,40 @@ class {{{classname}}} { {{>dart_constructor}} - - {{#vars}} +{{#vars}} {{#description}} /// {{{.}}} {{/description}} {{^isEnum}} {{#minimum}} - // minimum: {{{.}}} + {{#description}} + /// + {{/description}} + /// Minimum value: {{{.}}} {{/minimum}} {{#maximum}} - // maximum: {{{.}}} + {{#description}} + {{^minimum}} + /// + {{/minimum}} + {{/description}} + /// Maximum value: {{{.}}} {{/maximum}} + {{^isNullable}} + {{^required}} + {{^defaultValue}} + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + {{/defaultValue}} + {{/required}} + {{/isNullable}} {{/isEnum}} - {{{datatypeWithEnum}}} {{{name}}}; + {{{datatypeWithEnum}}}{{#isNullable}}?{{/isNullable}}{{^isNullable}}{{^required}}{{^defaultValue}}?{{/defaultValue}}{{/required}}{{/isNullable}} {{{name}}}; - {{/vars}} +{{/vars}} @override bool operator ==(Object other) => identical(this, other) || other is {{{classname}}} && {{#vars}} @@ -24,9 +43,9 @@ class {{{classname}}} { @override int get hashCode => - // ignore: unnecessary_parenthesis + // ignore: unnecessary_parenthesis {{#vars}} - ({{{name}}} == null ? 0 : {{{name}}}.hashCode){{^-last}} +{{/-last}}{{#-last}};{{/-last}} + ({{#isNullable}}{{{name}}} == null ? 0 : {{/isNullable}}{{^isNullable}}{{^required}}{{^defaultValue}}{{{name}}} == null ? 0 : {{/defaultValue}}{{/required}}{{/isNullable}}{{{name}}}{{#isNullable}}!{{/isNullable}}{{^isNullable}}{{^required}}{{^defaultValue}}!{{/defaultValue}}{{/required}}{{/isNullable}}.hashCode){{^-last}} +{{/-last}}{{#-last}};{{/-last}} {{/vars}} @override @@ -35,37 +54,51 @@ class {{{classname}}} { Map toJson() { final json = {}; {{#vars}} - {{^required}} + {{#isNullable}} if ({{{name}}} != null) { - {{/required}} + {{/isNullable}} + {{^isNullable}} + {{^required}} + {{^defaultValue}} + if ({{{name}}} != null) { + {{/defaultValue}} + {{/required}} + {{/isNullable}} {{#isDateTime}} {{#pattern}} - json[r'{{{baseName}}}'] = {{#required}}{{#isNullable}}{{{name}}} == null ? null : {{/isNullable}}{{/required}}_dateEpochMarker == '{{{pattern}}}' - ? {{{name}}}.millisecondsSinceEpoch - : {{{name}}}.toUtc().toIso8601String(); + json[r'{{{baseName}}}'] = _dateEpochMarker == '{{{pattern}}}' + ? {{{name}}}{{#isNullable}}!{{/isNullable}}{{^isNullable}}{{^required}}{{^defaultValue}}!{{/defaultValue}}{{/required}}{{/isNullable}}.millisecondsSinceEpoch + : {{{name}}}{{#isNullable}}!{{/isNullable}}{{^isNullable}}{{^required}}{{^defaultValue}}!{{/defaultValue}}{{/required}}{{/isNullable}}.toUtc().toIso8601String(); {{/pattern}} {{^pattern}} - json[r'{{{baseName}}}'] = {{#required}}{{#isNullable}}{{{name}}} == null ? null : {{/isNullable}}{{/required}}{{{name}}}.toUtc().toIso8601String(); + json[r'{{{baseName}}}'] = {{{name}}}{{#isNullable}}!{{/isNullable}}{{^isNullable}}{{^required}}{{^defaultValue}}!{{/defaultValue}}{{/required}}{{/isNullable}}.toUtc().toIso8601String(); {{/pattern}} {{/isDateTime}} {{#isDate}} {{#pattern}} - json[r'{{{baseName}}}'] = {{#required}}{{#isNullable}}{{{name}}} == null ? null : {{/isNullable}}{{/required}}_dateEpochMarker == '{{{pattern}}}' - ? {{{name}}}.millisecondsSinceEpoch - : _dateFormatter.format({{{name}}}.toUtc()); + json[r'{{{baseName}}}'] = _dateEpochMarker == '{{{pattern}}}' + ? {{{name}}}{{#isNullable}}!{{/isNullable}}{{^isNullable}}{{^required}}{{^defaultValue}}!{{/defaultValue}}{{/required}}{{/isNullable}}.millisecondsSinceEpoch + : _dateFormatter.format({{{name}}}{{#isNullable}}!{{/isNullable}}{{^isNullable}}{{^required}}{{^defaultValue}}!{{/defaultValue}}{{/required}}{{/isNullable}}.toUtc()); {{/pattern}} {{^pattern}} - json[r'{{{baseName}}}'] = {{#required}}{{#isNullable}}{{{name}}} == null ? null : {{/isNullable}}{{/required}}_dateFormatter.format({{{name}}}.toUtc()); + json[r'{{{baseName}}}'] = _dateFormatter.format({{{name}}}{{#isNullable}}!{{/isNullable}}{{^isNullable}}{{^required}}{{^defaultValue}}!{{/defaultValue}}{{/required}}{{/isNullable}}.toUtc()); {{/pattern}} {{/isDate}} {{^isDateTime}} {{^isDate}} - json[r'{{{baseName}}}'] = {{#required}}{{#isNullable}}{{{name}}} == null ? null : {{/isNullable}}{{/required}}{{{name}}}; + json[r'{{{baseName}}}'] = {{{name}}}; {{/isDate}} {{/isDateTime}} - {{^required}} + {{#isNullable}} + } + {{/isNullable}} + {{^isNullable}} + {{^required}} + {{^defaultValue}} } - {{/required}} + {{/defaultValue}} + {{/required}} + {{/isNullable}} {{/vars}} return json; } @@ -73,16 +106,28 @@ class {{{classname}}} { /// Returns a new [{{{classname}}}] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static {{{classname}}} fromJson(dynamic value) { + static {{{classname}}}? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "{{{classname}}}[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "{{{classname}}}[$key]" has a null value in JSON.'); + }); + return true; + }()); + return {{{classname}}}( {{#vars}} {{#isDateTime}} - {{{name}}}: mapDateTime(json, r'{{{baseName}}}', '{{{pattern}}}'), + {{{name}}}: mapDateTime(json, r'{{{baseName}}}', '{{{pattern}}}'){{#required}}{{^isNullable}}!{{/isNullable}}{{/required}}{{^required}}{{#defaultValue}} ?? {{{.}}}{{/defaultValue}}{{/required}}, {{/isDateTime}} {{#isDate}} - {{{name}}}: mapDateTime(json, r'{{{baseName}}}', '{{{pattern}}}'), + {{{name}}}: mapDateTime(json, r'{{{baseName}}}', '{{{pattern}}}'){{#required}}{{^isNullable}}!{{/isNullable}}{{/required}}{{^required}}{{#defaultValue}} ?? {{{.}}}{{/defaultValue}}{{/required}}, {{/isDate}} {{^isDateTime}} {{^isDate}} @@ -97,36 +142,36 @@ class {{{classname}}} { {{^items.complexType}} (e) => e == null ? null : (e as List).cast<{{items.items.dataType}}>() {{/items.complexType}} - ).toList(growable: false) + ).toList() : null, {{/items.isArray}} {{^items.isArray}} - {{{name}}}: {{{complexType}}}.listFromJson(json[r'{{{baseName}}}']), + {{{name}}}: {{{complexType}}}.listFromJson(json[r'{{{baseName}}}']){{#required}}{{^isNullable}}!{{/isNullable}}{{/required}}{{^required}}{{#defaultValue}} ?? {{{.}}}{{/defaultValue}}{{/required}}, {{/items.isArray}} {{/isArray}} {{^isArray}} {{#isMap}} {{#items.isArray}} {{{name}}}: json[r'{{{baseName}}}'] == null - ? null + ? {{#defaultValue}}{{{.}}}{{/defaultValue}}{{^defaultValue}}null{{/defaultValue}} {{#items.complexType}} - : {{items.complexType}}.mapListFromJson(json[r'{{{baseName}}}']), + : {{items.complexType}}.mapListFromJson(json[r'{{{baseName}}}']), {{/items.complexType}} {{^items.complexType}} - : mapCastOfType(json, r'{{{baseName}}}'), + : mapCastOfType(json, r'{{{baseName}}}'), {{/items.complexType}} {{/items.isArray}} {{^items.isArray}} {{#items.isMap}} {{#items.complexType}} - {{{name}}}: {{items.complexType}}.mapFromJson(json[r'{{{baseName}}}']), + {{{name}}}: {{items.complexType}}.mapFromJson(json[r'{{{baseName}}}']){{#required}}{{^isNullable}}!{{/isNullable}}{{/required}}{{^required}}{{#defaultValue}} ?? {{{.}}}{{/defaultValue}}{{/required}}, {{/items.complexType}} {{^items.complexType}} - {{{name}}}: mapCastOfType(json, r'{{{baseName}}}'), + {{{name}}}: mapCastOfType(json, r'{{{baseName}}}'){{#required}}{{^isNullable}}!{{/isNullable}}{{/required}}{{^required}}{{#defaultValue}} ?? {{{.}}}{{/defaultValue}}{{/required}}, {{/items.complexType}} {{/items.isMap}} {{^items.isMap}} - {{{name}}}: mapValueOfType<{{{datatypeWithEnum}}}>(json, r'{{{baseName}}}'), + {{{name}}}: mapValueOfType<{{{datatypeWithEnum}}}>(json, r'{{{baseName}}}'){{#required}}{{^isNullable}}!{{/isNullable}}{{/required}}{{^required}}{{#defaultValue}} ?? {{{.}}}{{/defaultValue}}{{/required}}, {{/items.isMap}} {{/items.isArray}} {{/isMap}} @@ -135,7 +180,7 @@ class {{{classname}}} { {{{name}}}: null, // No support for decoding binary content from JSON {{/isBinary}} {{^isBinary}} - {{{name}}}: {{{complexType}}}.fromJson(json[r'{{{baseName}}}']), + {{{name}}}: {{{complexType}}}.fromJson(json[r'{{{baseName}}}']){{#required}}{{^isNullable}}!{{/isNullable}}{{/required}}{{^required}}{{#defaultValue}} ?? {{{.}}}{{/defaultValue}}{{/required}}, {{/isBinary}} {{/isMap}} {{/isArray}} @@ -143,30 +188,30 @@ class {{{classname}}} { {{^complexType}} {{#isArray}} {{#isEnum}} - {{{name}}}: {{{items.datatypeWithEnum}}}.listFromJson(json[r'{{{baseName}}}']), + {{{name}}}: {{{items.datatypeWithEnum}}}.listFromJson(json[r'{{{baseName}}}']){{#required}}{{^isNullable}}!{{/isNullable}}{{/required}}{{^required}}{{#defaultValue}} ?? {{{.}}}{{/defaultValue}}{{/required}}, {{/isEnum}} {{^isEnum}} {{{name}}}: json[r'{{{baseName}}}'] is {{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}} - ? (json[r'{{{baseName}}}'] as {{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}).cast<{{{items.datatype}}}>() - : null, + ? (json[r'{{{baseName}}}'] as {{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}).cast<{{{items.datatype}}}>() + : {{#defaultValue}}{{{.}}}{{/defaultValue}}{{^defaultValue}}null{{/defaultValue}}, {{/isEnum}} {{/isArray}} {{^isArray}} {{#isMap}} - {{{name}}}: mapCastOfType(json, r'{{{baseName}}}'), + {{{name}}}: mapCastOfType(json, r'{{{baseName}}}'){{#required}}{{^isNullable}}!{{/isNullable}}{{/required}}{{^required}}{{#defaultValue}} ?? {{{.}}}{{/defaultValue}}{{/required}}, {{/isMap}} {{^isMap}} {{#isNumber}} {{{name}}}: json[r'{{{baseName}}}'] == null - ? null - : {{{datatypeWithEnum}}}.parse(json[r'{{{baseName}}}'].toString()), + ? {{#defaultValue}}{{{.}}}{{/defaultValue}}{{^defaultValue}}null{{/defaultValue}} + : {{{datatypeWithEnum}}}.parse(json[r'{{{baseName}}}'].toString()), {{/isNumber}} {{^isNumber}} {{^isEnum}} - {{{name}}}: mapValueOfType<{{{datatypeWithEnum}}}>(json, r'{{{baseName}}}'), + {{{name}}}: mapValueOfType<{{{datatypeWithEnum}}}>(json, r'{{{baseName}}}'){{#required}}{{^isNullable}}!{{/isNullable}}{{/required}}{{^required}}{{#defaultValue}} ?? {{{.}}}{{/defaultValue}}{{/required}}, {{/isEnum}} {{#isEnum}} - {{{name}}}: {{{enumName}}}.fromJson(json[r'{{{baseName}}}']), + {{{name}}}: {{{enumName}}}.fromJson(json[r'{{{baseName}}}']){{#required}}{{^isNullable}}!{{/isNullable}}{{/required}}{{^required}}{{#defaultValue}} ?? {{{.}}}{{/defaultValue}}{{/required}}, {{/isEnum}} {{/isNumber}} {{/isMap}} @@ -180,37 +225,56 @@ class {{{classname}}} { return null; } - static List<{{{classname}}}> listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map({{{classname}}}.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : <{{{classname}}}>[]; + static List<{{{classname}}}>? listFromJson(dynamic json, {bool growable = false,}) { + final result = <{{{classname}}}>[]; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = {{{classname}}}.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = {{{classname}}}.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = {{{classname}}}.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of {{{classname}}}-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = {{{classname}}}.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = {{{classname}}}.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { +{{#vars}} + {{#required}} + '{{{baseName}}}', + {{/required}} +{{/vars}} + }; } {{#vars}} {{#isEnum}} @@ -225,4 +289,4 @@ class {{{classname}}} { {{/mostInnerItems}} {{/isContainer}} {{/isEnum}} -{{/vars}} \ No newline at end of file +{{/vars}} diff --git a/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_enum.mustache b/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_enum.mustache index f686a20a2f69..6f4b8a62eda9 100644 --- a/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_enum.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_enum.mustache @@ -7,7 +7,7 @@ class {{{classname}}} { final {{{dataType}}} value; @override - String toString() => {{#isString}}value ?? ''{{/isString}}{{^isString}}value == null ? '' : value.toString(){{/isString}}; + String toString() => {{#isString}}value{{/isString}}{{^isString}}value.toString(){{/isString}}; {{{dataType}}} toJson() => value; @@ -26,13 +26,20 @@ class {{{classname}}} { {{/allowableValues}} ]; - static {{{classname}}} fromJson(dynamic value) => - {{{classname}}}TypeTransformer().decode(value); + static {{{classname}}}? fromJson(dynamic value) => {{{classname}}}TypeTransformer().decode(value); - static List<{{{classname}}}> listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map({{{classname}}}.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : <{{{classname}}}>[]; + static List<{{{classname}}}>? listFromJson(dynamic json, {bool growable = false,}) { + final result = <{{{classname}}}>[]; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = {{{classname}}}.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } } /// Transformation class that can [encode] an instance of [{{{classname}}}] to {{{dataType}}}, @@ -52,7 +59,7 @@ class {{{classname}}}TypeTransformer { /// /// The [allowNull] is very handy when an API changes and a new enum value is added or removed, /// and users are still using an old app with the old code. - {{{classname}}} decode(dynamic data, {bool allowNull}) { + {{{classname}}}? decode(dynamic data, {bool allowNull = true}) { if (data != null) { switch (data.toString()) { {{#allowableValues}} @@ -61,7 +68,7 @@ class {{{classname}}}TypeTransformer { {{/enumVars}} {{/allowableValues}} default: - if (allowNull == false) { + if (!allowNull) { throw ArgumentError('Unknown enum value to decode: $data'); } } @@ -70,5 +77,5 @@ class {{{classname}}}TypeTransformer { } /// Singleton [{{{classname}}}TypeTransformer] instance. - static {{{classname}}}TypeTransformer _instance; + static {{{classname}}}TypeTransformer? _instance; } diff --git a/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_enum_inline.mustache b/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_enum_inline.mustache index d01b1676aadd..b434d2d018ff 100644 --- a/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_enum_inline.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_enum_inline.mustache @@ -7,7 +7,7 @@ class {{{enumName}}} { final {{{dataType}}} value; @override - String toString() => {{#isString}}value ?? ''{{/isString}}{{^isString}}value == null ? '' : value.toString(){{/isString}}; + String toString() => {{#isString}}value{{/isString}}{{^isString}}value.toString(){{/isString}}; {{{dataType}}} toJson() => value; @@ -26,13 +26,20 @@ class {{{enumName}}} { {{/allowableValues}} ]; - static {{{enumName}}} fromJson(dynamic value) => - {{{enumName}}}TypeTransformer().decode(value); + static {{{enumName}}}? fromJson(dynamic value) => {{{enumName}}}TypeTransformer().decode(value); - static List<{{{enumName}}}> listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map({{{enumName}}}.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : <{{{enumName}}}>[]; + static List<{{{enumName}}}>? listFromJson(dynamic json, {bool growable = false,}) { + final result = <{{{enumName}}}>[]; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = {{{enumName}}}.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } } /// Transformation class that can [encode] an instance of [{{{enumName}}}] to {{{dataType}}}, @@ -52,7 +59,7 @@ class {{{enumName}}}TypeTransformer { /// /// The [allowNull] is very handy when an API changes and a new enum value is added or removed, /// and users are still using an old app with the old code. - {{{enumName}}} decode(dynamic data, {bool allowNull}) { + {{{enumName}}}? decode(dynamic data, {bool allowNull = true}) { if (data != null) { switch (data.toString()) { {{#allowableValues}} @@ -61,7 +68,7 @@ class {{{enumName}}}TypeTransformer { {{/enumVars}} {{/allowableValues}} default: - if (allowNull == false) { + if (!allowNull) { throw ArgumentError('Unknown enum value to decode: $data'); } } @@ -70,5 +77,5 @@ class {{{enumName}}}TypeTransformer { } /// Singleton [{{{enumName}}}TypeTransformer] instance. - static {{{enumName}}}TypeTransformer _instance; + static {{{enumName}}}TypeTransformer? _instance; } diff --git a/modules/openapi-generator/src/main/resources/dart2/travis.mustache b/modules/openapi-generator/src/main/resources/dart2/travis.mustache index 1a3af66d54c7..2774ccbba0e9 100644 --- a/modules/openapi-generator/src/main/resources/dart2/travis.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/travis.mustache @@ -6,7 +6,7 @@ language: dart dart: # Install a specific stable release -- "2.2.0" +- "2.12" install: - pub get diff --git a/pom.xml b/pom.xml index 8a40d41061f1..e6463ca0bc08 100644 --- a/pom.xml +++ b/pom.xml @@ -1400,7 +1400,6 @@ samples/openapi3/client/petstore/dart2/petstore_client_lib - samples/openapi3/client/petstore/dart2/petstore samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake diff --git a/samples/openapi3/client/petstore/dart2/petstore/README.md b/samples/openapi3/client/petstore/dart2/petstore/README.md deleted file mode 100644 index 2139c301745c..000000000000 --- a/samples/openapi3/client/petstore/dart2/petstore/README.md +++ /dev/null @@ -1,37 +0,0 @@ -# Background - -## Current state of tests - -TL;DR currently the only tests are e2e tests that were adapted to use a faked http client. While pushing data around as a smoke test has some value, more testing is required. In particular we need comprehensive unit/integration tests. - -- an old set of e2e tests are skipped for CI, as they hit a live endpoint and so are inherently flaky - - `pet_test.dart` - - `store_test.dart` - - `user_test.dart` -- the above set of tests were adapted to use a faked http client - - the tests are not really well suited to being used with a stubbed client, many are basically just testing the endpoint logic - - while not a great set of tests, they do have some value as a smoke test for template changes -- the adapted tests and files that contain test data: - - `pet_test_fake_client.dart` - - `store_test_fake_client.dart` - - `user_test_fake_client.dart` - - `fake_client.dart` - - `file_upload_response.json` - -## Assumptions - -- the tests will be run as part of CI and so have access to dart:io - -# Running - -## If not already done, resolve dependencies - -`pub get` - -## To run tests in a single file: - -`pub run test test/pet_test.dart` - -## To run all tests in the test folder: - -`pub run test` diff --git a/samples/openapi3/client/petstore/dart2/petstore/pom.xml b/samples/openapi3/client/petstore/dart2/petstore/pom.xml deleted file mode 100644 index c4ce7b4d68e7..000000000000 --- a/samples/openapi3/client/petstore/dart2/petstore/pom.xml +++ /dev/null @@ -1,73 +0,0 @@ - - 4.0.0 - org.openapitools - Dart2PetstoreClientTests - pom - 1.0.0-SNAPSHOT - Dart2 Petstore Client - - - - maven-dependency-plugin - - - package - - copy-dependencies - - - ${project.build.directory} - - - - - - org.codehaus.mojo - exec-maven-plugin - 1.2.1 - - - export-dartfmt - pre-install-test - - exec - - - export - - DART_FMT_PATH=/usr/local/bin/dartfmt - - - - - pub-get - pre-integration-test - - exec - - - pub - - get - - - - - pub-test - integration-test - - exec - - - pub - - run - test - - - - - - - - diff --git a/samples/openapi3/client/petstore/dart2/petstore/pubspec.lock b/samples/openapi3/client/petstore/dart2/petstore/pubspec.lock deleted file mode 100644 index dd5bbc89254b..000000000000 --- a/samples/openapi3/client/petstore/dart2/petstore/pubspec.lock +++ /dev/null @@ -1,418 +0,0 @@ -# Generated by pub -# See https://dart.dev/tools/pub/glossary#lockfile -packages: - _fe_analyzer_shared: - dependency: transitive - description: - name: _fe_analyzer_shared - url: "https://pub.dartlang.org" - source: hosted - version: "14.0.0" - analyzer: - dependency: transitive - description: - name: analyzer - url: "https://pub.dartlang.org" - source: hosted - version: "0.41.2" - args: - dependency: transitive - description: - name: args - url: "https://pub.dartlang.org" - source: hosted - version: "2.1.1" - async: - dependency: transitive - description: - name: async - url: "https://pub.dartlang.org" - source: hosted - version: "2.7.0" - boolean_selector: - dependency: transitive - description: - name: boolean_selector - url: "https://pub.dartlang.org" - source: hosted - version: "2.1.0" - build: - dependency: transitive - description: - name: build - url: "https://pub.dartlang.org" - source: hosted - version: "1.6.2" - built_collection: - dependency: transitive - description: - name: built_collection - url: "https://pub.dartlang.org" - source: hosted - version: "5.1.0" - built_value: - dependency: transitive - description: - name: built_value - url: "https://pub.dartlang.org" - source: hosted - version: "8.1.1" - charcode: - dependency: transitive - description: - name: charcode - url: "https://pub.dartlang.org" - source: hosted - version: "1.3.1" - cli_util: - dependency: transitive - description: - name: cli_util - url: "https://pub.dartlang.org" - source: hosted - version: "0.3.3" - clock: - dependency: transitive - description: - name: clock - url: "https://pub.dartlang.org" - source: hosted - version: "1.1.0" - code_builder: - dependency: transitive - description: - name: code_builder - url: "https://pub.dartlang.org" - source: hosted - version: "3.7.0" - collection: - dependency: "direct dev" - description: - name: collection - url: "https://pub.dartlang.org" - source: hosted - version: "1.15.0" - convert: - dependency: transitive - description: - name: convert - url: "https://pub.dartlang.org" - source: hosted - version: "3.0.1" - coverage: - dependency: transitive - description: - name: coverage - url: "https://pub.dartlang.org" - source: hosted - version: "0.15.2" - crypto: - dependency: transitive - description: - name: crypto - url: "https://pub.dartlang.org" - source: hosted - version: "3.0.1" - dart_style: - dependency: transitive - description: - name: dart_style - url: "https://pub.dartlang.org" - source: hosted - version: "1.3.12" - file: - dependency: transitive - description: - name: file - url: "https://pub.dartlang.org" - source: hosted - version: "6.1.2" - fixnum: - dependency: transitive - description: - name: fixnum - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.0" - glob: - dependency: transitive - description: - name: glob - url: "https://pub.dartlang.org" - source: hosted - version: "2.0.1" - http: - dependency: "direct dev" - description: - name: http - url: "https://pub.dartlang.org" - source: hosted - version: "0.13.3" - http_multi_server: - dependency: transitive - description: - name: http_multi_server - url: "https://pub.dartlang.org" - source: hosted - version: "3.0.1" - http_parser: - dependency: transitive - description: - name: http_parser - url: "https://pub.dartlang.org" - source: hosted - version: "4.0.0" - intl: - dependency: transitive - description: - name: intl - url: "https://pub.dartlang.org" - source: hosted - version: "0.17.0" - io: - dependency: transitive - description: - name: io - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.3" - js: - dependency: transitive - description: - name: js - url: "https://pub.dartlang.org" - source: hosted - version: "0.6.3" - logging: - dependency: transitive - description: - name: logging - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.1" - matcher: - dependency: transitive - description: - name: matcher - url: "https://pub.dartlang.org" - source: hosted - version: "0.12.10" - meta: - dependency: "direct dev" - description: - name: meta - url: "https://pub.dartlang.org" - source: hosted - version: "1.6.0" - mime: - dependency: transitive - description: - name: mime - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.0" - mockito: - dependency: "direct dev" - description: - name: mockito - url: "https://pub.dartlang.org" - source: hosted - version: "4.1.4" - node_preamble: - dependency: transitive - description: - name: node_preamble - url: "https://pub.dartlang.org" - source: hosted - version: "1.4.13" - openapi: - dependency: "direct main" - description: - path: "../petstore_client_lib" - relative: true - source: path - version: "1.0.0" - package_config: - dependency: transitive - description: - name: package_config - url: "https://pub.dartlang.org" - source: hosted - version: "1.9.3" - path: - dependency: transitive - description: - name: path - url: "https://pub.dartlang.org" - source: hosted - version: "1.8.0" - pedantic: - dependency: transitive - description: - name: pedantic - url: "https://pub.dartlang.org" - source: hosted - version: "1.11.1" - pool: - dependency: transitive - description: - name: pool - url: "https://pub.dartlang.org" - source: hosted - version: "1.5.0" - pub_semver: - dependency: transitive - description: - name: pub_semver - url: "https://pub.dartlang.org" - source: hosted - version: "2.0.0" - shelf: - dependency: transitive - description: - name: shelf - url: "https://pub.dartlang.org" - source: hosted - version: "1.2.0" - shelf_packages_handler: - dependency: transitive - description: - name: shelf_packages_handler - url: "https://pub.dartlang.org" - source: hosted - version: "3.0.0" - shelf_static: - dependency: transitive - description: - name: shelf_static - url: "https://pub.dartlang.org" - source: hosted - version: "1.1.0" - shelf_web_socket: - dependency: transitive - description: - name: shelf_web_socket - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.1" - source_gen: - dependency: transitive - description: - name: source_gen - url: "https://pub.dartlang.org" - source: hosted - version: "0.9.10+3" - source_map_stack_trace: - dependency: transitive - description: - name: source_map_stack_trace - url: "https://pub.dartlang.org" - source: hosted - version: "2.1.0" - source_maps: - dependency: transitive - description: - name: source_maps - url: "https://pub.dartlang.org" - source: hosted - version: "0.10.10" - source_span: - dependency: transitive - description: - name: source_span - url: "https://pub.dartlang.org" - source: hosted - version: "1.8.1" - stack_trace: - dependency: transitive - description: - name: stack_trace - url: "https://pub.dartlang.org" - source: hosted - version: "1.10.0" - stream_channel: - dependency: transitive - description: - name: stream_channel - url: "https://pub.dartlang.org" - source: hosted - version: "2.1.0" - string_scanner: - dependency: transitive - description: - name: string_scanner - url: "https://pub.dartlang.org" - source: hosted - version: "1.1.0" - term_glyph: - dependency: transitive - description: - name: term_glyph - url: "https://pub.dartlang.org" - source: hosted - version: "1.2.0" - test: - dependency: "direct dev" - description: - name: test - url: "https://pub.dartlang.org" - source: hosted - version: "1.16.5" - test_api: - dependency: transitive - description: - name: test_api - url: "https://pub.dartlang.org" - source: hosted - version: "0.2.19" - test_core: - dependency: transitive - description: - name: test_core - url: "https://pub.dartlang.org" - source: hosted - version: "0.3.15" - typed_data: - dependency: transitive - description: - name: typed_data - url: "https://pub.dartlang.org" - source: hosted - version: "1.3.0" - vm_service: - dependency: transitive - description: - name: vm_service - url: "https://pub.dartlang.org" - source: hosted - version: "6.2.0" - watcher: - dependency: transitive - description: - name: watcher - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.0" - web_socket_channel: - dependency: transitive - description: - name: web_socket_channel - url: "https://pub.dartlang.org" - source: hosted - version: "2.1.0" - webkit_inspection_protocol: - dependency: transitive - description: - name: webkit_inspection_protocol - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.0" - yaml: - dependency: transitive - description: - name: yaml - url: "https://pub.dartlang.org" - source: hosted - version: "3.1.0" -sdks: - dart: ">=2.12.0 <3.0.0" diff --git a/samples/openapi3/client/petstore/dart2/petstore/pubspec.yaml b/samples/openapi3/client/petstore/dart2/petstore/pubspec.yaml deleted file mode 100644 index 6b1e0dcfa3a2..000000000000 --- a/samples/openapi3/client/petstore/dart2/petstore/pubspec.yaml +++ /dev/null @@ -1,19 +0,0 @@ -name: petstore_client -version: 1.0.0 -description: Petstore client using OpenAPI library - -publish_to: none - -environment: - sdk: '>=2.11.0 <3.0.0' - -dependencies: - openapi: - path: ../petstore_client_lib - -dev_dependencies: - meta: <1.7.0 - test: ^1.8.0 - mockito: ^4.1.1 - http: ^0.13.0 - collection: ^1.14.12 diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/fake_client.dart b/samples/openapi3/client/petstore/dart2/petstore/test/fake_client.dart deleted file mode 100644 index ed60f386aa41..000000000000 --- a/samples/openapi3/client/petstore/dart2/petstore/test/fake_client.dart +++ /dev/null @@ -1,134 +0,0 @@ -import 'dart:convert'; - -import 'package:collection/collection.dart'; -import 'package:http/http.dart'; -import 'package:mockito/mockito.dart'; - -/// A fake client that checks for expected values and returns given responses -/// -/// Checks for the expected values (url, headers, body) and throws if not found -/// -/// If exception is non-null the request will throw the exception, after other -/// checks are performed -class FakeClient extends Fake implements Client { - FakeClient({ - this.throwException, - this.expectedPostRequestBody, - this.postResponseBody, - this.expectedGetRequestBody, - this.getResponseBody, - this.deleteResponseBody, - this.expectedPutRequestBody, - this.putResponseBody, - this.sendResponseBody, - String expectedUrl, - this.expectedHeaders = null, - }) : this.expectedUrl = Uri.parse(expectedUrl); - - Exception throwException; - Object expectedPostRequestBody; - String postResponseBody; - String expectedGetRequestBody; - String getResponseBody; - String deleteResponseBody; - String expectedPutRequestBody; - String putResponseBody; - String sendResponseBody; - Uri expectedUrl; - Map expectedHeaders; - - @override - Future post(Uri url, - {Map headers, Object body, Encoding encoding}) async { - // check that the request was made with expected values - if (url != expectedUrl) { - throw StateError( - 'POST was called with unexpected url: ${url} should be ${expectedUrl}'); - } - if (!MapEquality().equals(headers, expectedHeaders)) { - throw StateError( - 'POST was called with unexpected headers: ${headers} should be ${expectedHeaders}'); - } - // currently we only expect Map (and subtypes) or Strings - if (body is Map) { - if (!MapEquality().equals(body, expectedPostRequestBody)) { - throw StateError( - 'POST was called with unexpected body: ${body} should be ${expectedPostRequestBody}'); - } - } else if (body != expectedPostRequestBody) { - throw StateError( - 'POST was called with unexpected body: ${body} should be ${expectedPostRequestBody}'); - } - - // throw if set to throw - if (throwException != null) throw throwException; - - return Response(postResponseBody, 200); - } - - @override - Future get(Uri url, {Map headers}) async { - // check that the request was made with expected values - if (url != expectedUrl) { - throw StateError( - 'GET was called with unexpected url: ${url} should be ${expectedUrl}'); - } - if (!MapEquality().equals(headers, expectedHeaders)) { - throw StateError( - 'GET was called with unexpected headers: ${headers} should be ${expectedHeaders}'); - } - - // throw if set to throw - if (throwException != null) throw throwException; - - return Response(getResponseBody, 200); - } - - @override - Future delete(Uri url, - {Map headers, Object body, Encoding encoding}) async { - // check that the request was made with expected values - if (url != expectedUrl) { - throw StateError( - 'DELETE was called with unexpected url: ${url} should be ${expectedUrl}'); - } - if (!MapEquality().equals(headers, expectedHeaders)) { - throw StateError( - 'DELETE was called with unexpected headers: ${headers} should be ${expectedHeaders}'); - } - - // throw if set to throw - if (throwException != null) throw throwException; - - return Response(deleteResponseBody, 200); - } - - @override - Future put(Uri url, - {Map headers, Object body, Encoding encoding}) async { - // check that the request was made with expected values - if (url != expectedUrl) { - throw StateError( - 'PUT was called with unexpected url: ${url} should be ${expectedUrl}'); - } - if (!MapEquality().equals(headers, expectedHeaders)) { - throw StateError( - 'PUT was called with unexpected headers: ${headers} should be ${expectedHeaders}'); - } - if (body != expectedPutRequestBody) { - throw StateError( - 'PUT was called with unexpected body: ${body} should be ${expectedPutRequestBody}'); - } - - // throw if set to throw - if (throwException != null) throw throwException; - - return Response(putResponseBody, 200); - } - - @override - Future send(BaseRequest request) async { - List bytes = utf8.encode(sendResponseBody); - return StreamedResponse(Stream.fromIterable([bytes]), 200); - } -} diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/file_upload_response.json b/samples/openapi3/client/petstore/dart2/petstore/test/file_upload_response.json deleted file mode 100644 index 8855b00d9e38..000000000000 --- a/samples/openapi3/client/petstore/dart2/petstore/test/file_upload_response.json +++ /dev/null @@ -1 +0,0 @@ -{"code":200,"type":"unknown","message":"additionalMetadata: \nFile uploaded to ./null, 4 bytes"} \ No newline at end of file diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/inventory_response.json b/samples/openapi3/client/petstore/dart2/petstore/test/inventory_response.json deleted file mode 100644 index b4388d1e7b35..000000000000 --- a/samples/openapi3/client/petstore/dart2/petstore/test/inventory_response.json +++ /dev/null @@ -1 +0,0 @@ -{"mine":1,"sold":18,"string":568,"Dead":2,"test":2,"Nonavailable":1,"custom":3,"pending":20,"available":2212,"notAvailable":26,"avaiflable":1,"AVAILABLE":1,"swimming":1,"availablee":2,"success":1,"105":1,"missing":11,"disabled":1,"Available":1,"]]>":1} \ No newline at end of file diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/order_model_test.dart b/samples/openapi3/client/petstore/dart2/petstore/test/order_model_test.dart deleted file mode 100644 index 7048659e8942..000000000000 --- a/samples/openapi3/client/petstore/dart2/petstore/test/order_model_test.dart +++ /dev/null @@ -1,9 +0,0 @@ -import 'package:openapi/api.dart'; -import 'package:test/test.dart'; - -void main() { - test('Check if default value is generated', () async { - var order = Order(); - expect(order.complete, equals(false)); - }); -} diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/pet_faked_client_test.dart b/samples/openapi3/client/petstore/dart2/petstore/test/pet_faked_client_test.dart deleted file mode 100644 index 9737df5d4881..000000000000 --- a/samples/openapi3/client/petstore/dart2/petstore/test/pet_faked_client_test.dart +++ /dev/null @@ -1,223 +0,0 @@ -import 'dart:io'; - -import 'package:http/http.dart'; -import 'package:openapi/api.dart'; -import 'package:test/test.dart'; - -import 'fake_client.dart'; -import 'random_id.dart'; - -void main() { - final petApi = PetApi(); - - Pet makePet({ - int id = 1234, - String name = 'Fluffy', - String status = '', - }) { - final category = Category() - ..id = 1234 - ..name = 'eyeColor'; - final tags = [ - Tag() - ..id = 1234 - ..name = 'New York', - Tag() - ..id = 124321 - ..name = 'Jose' - ]; - return Pet(name: name) - ..id = id - ..category = category - ..tags = tags - ..status = PetStatusEnum.fromJson(status) - ..photoUrls = ['https://petstore.com/sample/photo1.jpg']; - } - - /// Setup the fake client then call [petApi.addPet] - Future addPet(Pet pet) async { - petApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: await petApi.apiClient.serializeAsync(pet), - postResponseBody: await petApi.apiClient.serializeAsync(pet), - expectedHeaders: {'Content-Type': 'application/json'}); - return petApi.addPet(pet); - } - - group('Pet API with faked client', () { - test('adds a new pet and gets it by id', () async { - final id = newId(); - final newPet = makePet(id: id); - - // use the pet api to add a pet - petApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: await petApi.apiClient.serializeAsync(newPet), - postResponseBody: await petApi.apiClient.serializeAsync(newPet), - expectedHeaders: {'Content-Type': 'application/json'}); - await petApi.addPet(newPet); - - // retrieve the same pet by id - petApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/pet/$id', - getResponseBody: await petApi.apiClient.serializeAsync(newPet), - ); - final retrievedPet = await petApi.getPetById(id); - - // check that the retrieved id is as expected - expect(retrievedPet.id, equals(id)); - }); - - test('doesn\'t get non-existing pet by id', () { - final id = newId(); - petApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/pet/$id', - throwException: ApiException(400, 'not found'), - ); - expect(petApi.getPetById(id), throwsA(equals(TypeMatcher()))); - }); - - test('deletes existing pet by id', () async { - final id = newId(); - Pet newPet = makePet(id: id); - - // add a new pet - petApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: await petApi.apiClient.serializeAsync(newPet), - postResponseBody: await petApi.apiClient.serializeAsync(newPet), - expectedHeaders: {'Content-Type': 'application/json'}); - await petApi.addPet(newPet); - - // delete the pet - petApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/pet/$id', - expectedHeaders: {'api_key': 'special-key'}, - deleteResponseBody: '', - ); - await petApi.deletePet(id, apiKey: 'special-key'); - - // check for the deleted pet - petApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/pet/$id', - throwException: ApiException(400, 'Not found'), - ); - expect(petApi.getPetById(id), throwsA(equals(TypeMatcher()))); - }); - - test('updates pet with form', () async { - final id = newId(); - final newPet = makePet(id: id, name: 'Snowy'); - - // add a new pet - petApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: await petApi.apiClient.serializeAsync(newPet), - postResponseBody: await petApi.apiClient.serializeAsync(newPet), - expectedHeaders: {'Content-Type': 'application/json'}); - await petApi.addPet(newPet); - - // update with form - petApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/pet/$id', - expectedHeaders: { - 'Content-Type': 'application/x-www-form-urlencoded', - }, - expectedPostRequestBody: {'name': 'Doge', 'status': ''}, - postResponseBody: '', - ); - await petApi.updatePetWithForm(id, name: 'Doge', status: ''); - - // check update worked - newPet.name = 'Doge'; - petApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/pet/$id', - getResponseBody: await petApi.apiClient.serializeAsync(newPet), - ); - final pet = await petApi.getPetById(id); - expect(pet.name, equals('Doge')); - }); - - test('updates existing pet', () async { - final id = newId(); - final name = 'Snowy'; - final newPet = makePet(id: id); - final updatePet = makePet(id: id, name: name); - - // add a new pet - petApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: await petApi.apiClient.serializeAsync(newPet), - postResponseBody: await petApi.apiClient.serializeAsync(newPet), - expectedHeaders: {'Content-Type': 'application/json'}); - await petApi.addPet(newPet); - - // update the same pet - petApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPutRequestBody: await petApi.apiClient.serializeAsync(updatePet), - putResponseBody: await petApi.apiClient.serializeAsync(updatePet), - expectedHeaders: {'Content-Type': 'application/json'}); - await petApi.updatePet(updatePet); - - // check update worked - petApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/pet/$id', - getResponseBody: await petApi.apiClient.serializeAsync(updatePet), - ); - final pet = await petApi.getPetById(id); - expect(pet.name, equals(name)); - }); - - test('finds pets by status', () async { - final id1 = newId(); - final id2 = newId(); - final id3 = newId(); - final status = '${PetStatusEnum.available}'; - final pet1 = makePet(id: id1, status: status); - final pet2 = makePet(id: id2, status: status); - final pet3 = makePet(id: id3, status: '${PetStatusEnum.sold}'); - - await addPet(pet1); - await addPet(pet2); - await addPet(pet3); - - // retrieve pets by status - petApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/pet/findByStatus?status=$status', - getResponseBody: await petApi.apiClient.serializeAsync([pet1, pet2]), - ); - final pets = await petApi.findPetsByStatus([status]); - - // tests serialisation and deserialisation of enum - final petsByStatus = pets.where((p) => p.status == PetStatusEnum.available); - expect(petsByStatus.length, equals(2)); - final petIds = pets.map((pet) => pet.id).toList(); - expect(petIds, contains(id1)); - expect(petIds, contains(id2)); - expect(petIds, isNot(contains(id3))); - }); - - test('uploads a pet image', () async { - final id = newId(); - final newPet = makePet(id: id); - // get some test data (recorded from live response) - final uploadResponse = await File('test/file_upload_response.json').readAsString(); - - // add a new pet - petApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: await petApi.apiClient.serializeAsync(newPet), - postResponseBody: await petApi.apiClient.serializeAsync(newPet), - expectedHeaders: {'Content-Type': 'application/json'}); - await petApi.addPet(newPet); - - petApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/pet', - sendResponseBody: uploadResponse, - ); - final file = new MultipartFile.fromBytes('file', [104, 101, 108, 108, 111]); - await petApi.uploadFile(id, file: file); - }); - }); -} diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/pet_test.dart b/samples/openapi3/client/petstore/dart2/petstore/test/pet_test.dart deleted file mode 100644 index cbd26c68c7ee..000000000000 --- a/samples/openapi3/client/petstore/dart2/petstore/test/pet_test.dart +++ /dev/null @@ -1,101 +0,0 @@ -@Skip('Needs real petstore') -import 'package:http/http.dart'; -import 'package:openapi/api.dart'; -import 'package:test/test.dart'; - -import 'random_id.dart'; - -void main() { - var petApi = PetApi(); - - Pet makePet({ - int id = 1234, - String name = 'Fluffy', - String status = '', - }) { - final category = Category() - ..id = 1234 - ..name = 'eyeColor'; - final tags = [ - Tag() - ..id = 1234 - ..name = 'New York', - Tag() - ..id = 124321 - ..name = 'Jose' - ]; - - return Pet( - id: id, - category: category, - name: name, //required field - tags: tags, - photoUrls: ['https://petstore.com/sample/photo1.jpg'] //required field - ) - ..status = PetStatusEnum.fromJson(status) - ..photoUrls = ['https://petstore.com/sample/photo1.jpg']; - } - - group('Pet API with live client', () { - test('adds a new pet and gets it by id', () async { - var id = newId(); - await petApi.addPet(makePet(id: id)); - var pet = await petApi.getPetById(id); - expect(pet.id, equals(id)); - }); - - test('doesn\'t get non-existing pet by id', () { - expect(petApi.getPetById(newId()), throwsA(equals(TypeMatcher()))); - }); - - test('deletes existing pet by id', () async { - var id = newId(); - await petApi.addPet(makePet(id: id)); - await petApi.deletePet(id, apiKey: 'special-key'); - expect(petApi.getPetById(id), throwsA(equals(TypeMatcher()))); - }); - - test('updates pet with form', () async { - var id = newId(); - - await petApi.addPet(makePet(id: id, name: 'Snowy')); - await petApi.updatePetWithForm(id, name: 'Doge', status: ''); - var pet = await petApi.getPetById(id); - expect(pet.name, equals('Doge')); - }); - - test('updates existing pet', () async { - var id = newId(); - var name = 'Snowy'; - - await petApi.addPet(makePet(id: id)); - await petApi.updatePet(makePet(id: id, name: name)); - var pet = await petApi.getPetById(id); - expect(pet.name, equals(name)); - }); - - test('finds pets by status', () async { - var id1 = newId(); - var id2 = newId(); - var id3 = newId(); - var status = '${PetStatusEnum.available}'; - - await petApi.addPet(makePet(id: id1, status: status)); - await petApi.addPet(makePet(id: id2, status: status)); - await petApi.addPet(makePet(id: id3, status: '${PetStatusEnum.sold}')); - - var pets = await petApi.findPetsByStatus([status]); - var petIds = pets.map((pet) => pet.id).toList(); - expect(petIds, contains(id1)); - expect(petIds, contains(id2)); - expect(petIds, isNot(contains(id3))); - }); - - test('uploads a pet image', () async { - var id = newId(); - await petApi.addPet(makePet(id: id)); - var file = new MultipartFile.fromBytes('file', [104, 101, 108, 108, 111]); - await petApi.uploadFile(id, additionalMetadata: '', file: file); - }); - }); -} diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/random_id.dart b/samples/openapi3/client/petstore/dart2/petstore/test/random_id.dart deleted file mode 100644 index ca67ac209934..000000000000 --- a/samples/openapi3/client/petstore/dart2/petstore/test/random_id.dart +++ /dev/null @@ -1,7 +0,0 @@ -import 'dart:math'; - -final _random = new Random(); - -int newId() { - return _random.nextInt(999999); -} diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/store_faked_client_test.dart b/samples/openapi3/client/petstore/dart2/petstore/test/store_faked_client_test.dart deleted file mode 100644 index 541d08b8c6a7..000000000000 --- a/samples/openapi3/client/petstore/dart2/petstore/test/store_faked_client_test.dart +++ /dev/null @@ -1,83 +0,0 @@ -import 'dart:io'; - -import 'package:openapi/api.dart'; -import 'package:test/test.dart'; - -import 'fake_client.dart'; -import 'random_id.dart'; - -void main() { - var storeApi = new StoreApi(); - - Order makeOrder({int id}) { - return Order() - ..id = id - ..petId = 1234 - ..quantity = 1 - ..shipDate = DateTime.now() - ..status - ..complete = false; - } - - group('Store API with faked client', () { - test('places an order and gets it by id', () async { - final id = newId(); - final newOrder = makeOrder(id: id); - - // use the store api to add an order - storeApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/store/order', - expectedPostRequestBody: await storeApi.apiClient.serializeAsync(newOrder), - postResponseBody: await storeApi.apiClient.serializeAsync(newOrder), - expectedHeaders: {"Content-Type": "application/json"}); - await storeApi.placeOrder(newOrder); - - // retrieve the same order by id - storeApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/store/order/$id', - getResponseBody: await storeApi.apiClient.serializeAsync(newOrder), - ); - final placedOrder = await storeApi.getOrderById(id); - expect(placedOrder.id, equals(id)); - }); - - test('deletes an order', () async { - final id = newId(); - final newOrder = makeOrder(id: id); - - // use the store api to add an order - storeApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/store/order', - expectedPostRequestBody: await storeApi.apiClient.serializeAsync(newOrder), - postResponseBody: await storeApi.apiClient.serializeAsync(newOrder), - expectedHeaders: {"Content-Type": "application/json"}); - await storeApi.placeOrder(newOrder); - - // delete the same order - storeApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/store/order/$id', - deleteResponseBody: '', - ); - await storeApi.deleteOrder(id.toString()); - - // try and retrieve the order - storeApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/store/order/$id', - throwException: ApiException(400, 'Not found'), - ); - expect(storeApi.getOrderById(id), throwsA(equals(TypeMatcher()))); - }); - - test('gets the store inventory', () async { - // get some test data (recorded from live response) - final inventoryResponse = await File('test/inventory_response.json').readAsString(); - // use the store api to get the inventory - storeApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/store/inventory', - getResponseBody: inventoryResponse, - ); - Map inventory = await storeApi.getInventory(); - expect(inventory.length, isNot(equals(0))); - }); - }); -} diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/store_test.dart b/samples/openapi3/client/petstore/dart2/petstore/test/store_test.dart deleted file mode 100644 index a5b19cd1de59..000000000000 --- a/samples/openapi3/client/petstore/dart2/petstore/test/store_test.dart +++ /dev/null @@ -1,42 +0,0 @@ -@Skip('Needs real petstore') -import 'package:openapi/api.dart'; -import 'package:test/test.dart'; - -import 'random_id.dart'; - -void main() { - var storeApi = new StoreApi(); - - Order makeOrder({int id}) { - return Order() - ..id = id - ..petId = 1234 - ..quantity = 1 - ..shipDate = DateTime.now() - ..status - ..complete = false; - } - - group('Store API with live client', () { - test('places an order and gets it by id', () async { - var id = newId(); - - await storeApi.placeOrder(makeOrder(id: id)); - var order = await storeApi.getOrderById(id); - expect(order.id, equals(id)); - }); - - test('deletes an order', () async { - var id = newId(); - - await storeApi.placeOrder(makeOrder(id: id)); - await storeApi.deleteOrder(id.toString()); - expect(storeApi.getOrderById(id), throwsA(equals(TypeMatcher()))); - }); - - test('gets the store inventory', () async { - Map inventory = await storeApi.getInventory(); - expect(inventory.length, isNot(equals(0))); - }); - }); -} diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/user_faked_client_test.dart b/samples/openapi3/client/petstore/dart2/petstore/test/user_faked_client_test.dart deleted file mode 100644 index f81379351924..000000000000 --- a/samples/openapi3/client/petstore/dart2/petstore/test/user_faked_client_test.dart +++ /dev/null @@ -1,180 +0,0 @@ -import 'package:openapi/api.dart'; -import 'package:test/test.dart'; - -import 'fake_client.dart'; -import 'random_id.dart'; - -void main() { - var userApi = new UserApi(); - - User makeUser( - {int id, String userName = 'username', String password = 'password'}) { - return User() - ..id = id - ..username = userName - ..firstName = 'firstname' - ..lastName = 'lastname' - ..email = 'email' - ..password = password - ..phone = 'phone' - ..userStatus = 0; - } - - group('User API with faked client', () { - test('creates a user', () async { - final id = newId(); - final username = 'Mally45'; - final newUser = makeUser(id: id, userName: username); - - // use the user api to create a user - userApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/user', - expectedPostRequestBody: - await userApi.apiClient.serializeAsync(newUser), - expectedHeaders: {'Content-Type': 'application/json'}, - postResponseBody: await userApi.apiClient.serializeAsync(newUser), - ); - await userApi.createUser(newUser); - - // retrieve the same user - userApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/user/$username', - getResponseBody: await userApi.apiClient.serializeAsync(newUser), - ); - var user = await userApi.getUserByName(username); - expect(user.id, equals(id)); - }); - - test('creates users with list input', () async { - final firstId = newId(); - final joe = 'Joe'; - - final sally = 'Sally'; - final secondId = newId(); - - final users = [ - makeUser(id: firstId, userName: joe), - makeUser(id: secondId, userName: sally), - ]; - - // use the user api to create a list of users - userApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/user/createWithList', - expectedPostRequestBody: await userApi.apiClient.serializeAsync(users), - expectedHeaders: {'Content-Type': 'application/json'}, - postResponseBody: await userApi.apiClient.serializeAsync(users), - ); - await userApi.createUsersWithListInput(users); - - // retrieve the users - userApi.apiClient.client = FakeClient( - expectedUrl: - 'http://petstore.swagger.io/v2/user/${users.elementAt(0).username}', - getResponseBody: await userApi.apiClient.serializeAsync( - users.elementAt(0), - ), - ); - final firstUser = await userApi.getUserByName(joe); - userApi.apiClient.client = FakeClient( - expectedUrl: - 'http://petstore.swagger.io/v2/user/${users.elementAt(1).username}', - getResponseBody: await userApi.apiClient.serializeAsync( - users.elementAt(1), - ), - ); - final secondUser = await userApi.getUserByName(sally); - expect(firstUser.id, equals(firstId)); - expect(secondUser.id, equals(secondId)); - }); - - test('updates a user', () async { - final username = 'Arkjam89'; - final email = 'test@example.com'; - final newUser = makeUser(id: newId(), userName: username); - - // use the user api to create a user - userApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/user', - expectedPostRequestBody: - await userApi.apiClient.serializeAsync(newUser), - expectedHeaders: {'Content-Type': 'application/json'}, - postResponseBody: await userApi.apiClient.serializeAsync(newUser), - ); - await userApi.createUser(newUser); - newUser.email = email; - - // use the user api to update the user - userApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/user/${newUser.username}', - expectedPutRequestBody: await userApi.apiClient.serializeAsync(newUser), - expectedHeaders: {'Content-Type': 'application/json'}, - putResponseBody: await userApi.apiClient.serializeAsync(newUser), - ); - await userApi.updateUser(username, newUser); - - // retrieve the same user - userApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/user/${newUser.username}', - getResponseBody: await userApi.apiClient.serializeAsync(newUser), - ); - var foundUser = await userApi.getUserByName(username); - expect(foundUser.email, equals(email)); - }); - - test('deletes a user', () async { - final username = 'Riddlem325'; - final newUser = makeUser(id: newId(), userName: username); - - // use the user api to create a user - userApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/user', - expectedPostRequestBody: - await userApi.apiClient.serializeAsync(newUser), - expectedHeaders: {'Content-Type': 'application/json'}, - postResponseBody: await userApi.apiClient.serializeAsync(newUser), - ); - await userApi.createUser(newUser); - - // delete the same user - userApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/user/${newUser.username}', - deleteResponseBody: '', - ); - await userApi.deleteUser(username); - - // try and retrieve the user - userApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/user/${newUser.username}', - throwException: ApiException(400, 'Not found'), - ); - expect(userApi.getUserByName(username), - throwsA(TypeMatcher())); - }); - - test('logs a user in', () async { - final username = 'sgarad625'; - final password = 'lokimoki1'; - final newUser = - makeUser(id: newId(), userName: username, password: password); - - // use the user api to create a user - userApi.apiClient.client = FakeClient( - expectedUrl: 'http://petstore.swagger.io/v2/user', - expectedPostRequestBody: - await userApi.apiClient.serializeAsync(newUser), - expectedHeaders: {'Content-Type': 'application/json'}, - postResponseBody: await userApi.apiClient.serializeAsync(newUser), - ); - await userApi.createUser(newUser); - - // use the user api to login - userApi.apiClient.client = FakeClient( - expectedUrl: - 'http://petstore.swagger.io/v2/user/login?username=${newUser.username}&password=${newUser.password}', - getResponseBody: 'logged in user session:', - ); - final result = await userApi.loginUser(username, password); - expect(result, contains('logged in user session:')); - }); - }); -} diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/user_test.dart b/samples/openapi3/client/petstore/dart2/petstore/test/user_test.dart deleted file mode 100644 index d604363622d6..000000000000 --- a/samples/openapi3/client/petstore/dart2/petstore/test/user_test.dart +++ /dev/null @@ -1,79 +0,0 @@ -@Skip('Needs real petstore') -import 'package:openapi/api.dart'; -import 'package:test/test.dart'; - -import 'random_id.dart'; - -void main() { - var userApi = new UserApi(); - - User makeUser({int id, String userName = 'username', String password = 'password'}) { - return User() - ..id = id - ..username = userName - ..firstName = 'firstname' - ..lastName = 'lastname' - ..email = 'email' - ..password = password - ..phone = 'phone' - ..userStatus = 0; - } - - group('User API with live client', () { - test('creates a user', () async { - var id = newId(); - var username = 'Mally45'; - await userApi.createUser(makeUser(id: id, userName: username)); - var user = await userApi.getUserByName(username); - expect(user.id, equals(id)); - }); - - test('creates users with list input', () async { - var firstId = newId(); - var joe = 'Joe'; - - var sally = 'Sally'; - var secondId = newId(); - - var users = [ - makeUser(id: firstId, userName: joe), - makeUser(id: secondId, userName: sally), - ]; - - await userApi.createUsersWithListInput(users); - var firstUser = await userApi.getUserByName(joe); - var secondUser = await userApi.getUserByName(sally); - expect(firstUser.id, equals(firstId)); - expect(secondUser.id, equals(secondId)); - }); - - test('updates a user', () async { - var username = 'Arkjam89'; - var email = 'test@example.com'; - var user = makeUser(id: newId(), userName: username); - - await userApi.createUser(user); - user.email = email; - await userApi.updateUser(username, user); - var foundUser = await userApi.getUserByName(username); - expect(foundUser.email, equals(email)); - }); - - test('deletes a user', () async { - var username = 'Riddlem325'; - await userApi.createUser(makeUser(id: newId(), userName: username)); - await userApi.deleteUser(username); - expect(userApi.getUserByName(username), throwsA(TypeMatcher())); - }); - - test('logs a user in', () async { - var username = 'sgarad625'; - var password = 'lokimoki1'; - var user = makeUser(id: newId(), userName: username, password: password); - - await userApi.createUser(user); - var result = await userApi.loginUser(username, password); - expect(result, contains('logged in user session:')); - }); - }); -} diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/.gitignore b/samples/openapi3/client/petstore/dart2/petstore_client_lib/.gitignore index 8b7331fd822c..1be28ced0940 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/.gitignore +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/.gitignore @@ -1,27 +1,17 @@ -# See https://www.dartlang.org/tools/private-files.html +# See https://dart.dev/guides/libraries/private-files -# Files and directories created by pub -.buildlog +.dart_tool/ .packages -.project -.pub/ build/ -**/packages/ +pubspec.lock # Except for application packages -# Files created by dart2js -# (Most Dart developers will use pub build to compile Dart, use/modify these -# rules if you intend to use dart2js directly -# Convention is to use extension '.dart.js' for Dart compiled to Javascript to -# differentiate from explicit Javascript files) -*.dart.js -*.part.js -*.js.deps -*.js.map -*.info.json - -# Directory created by dartdoc doc/api/ -# Don't commit pubspec lock file -# (Library packages only! Remove pattern if developing an application package) -pubspec.lock +# IntelliJ +*.iml +*.ipr +*.iws +.idea/ + +# Mac +.DS_Store diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/.travis.yml b/samples/openapi3/client/petstore/dart2/petstore_client_lib/.travis.yml index 1a3af66d54c7..2774ccbba0e9 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/.travis.yml +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/.travis.yml @@ -6,7 +6,7 @@ language: dart dart: # Install a specific stable release -- "2.2.0" +- "2.12" install: - pub get diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/README.md b/samples/openapi3/client/petstore/dart2/petstore_client_lib/README.md index b41b8970d0c2..dd7e2f923537 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/README.md +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/README.md @@ -8,7 +8,7 @@ This Dart package is automatically generated by the [OpenAPI Generator](https:// ## Requirements -Dart 2.0 or later +Dart 2.12 or later ## Installation & Usage diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api.dart index e67b60f2670f..742bcfa11543 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/pet_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/pet_api.dart index 5b299b6b2cdb..b4ee176a9262 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/pet_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/pet_api.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -12,7 +12,7 @@ part of openapi.api; class PetApi { - PetApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; + PetApi([ApiClient? apiClient]) : apiClient = apiClient ?? defaultApiClient; final ApiClient apiClient; @@ -25,16 +25,11 @@ class PetApi { /// * [Pet] pet (required): /// Pet object that needs to be added to the store Future addPetWithHttpInfo(Pet pet,) async { - // Verify required params are set. - if (pet == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: pet'); - } - // ignore: prefer_const_declarations final path = r'/pet'; // ignore: prefer_final_locals - Object postBody = pet; + Object? postBody = pet; final queryParams = []; final headerParams = {}; @@ -51,7 +46,7 @@ class PetApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -62,7 +57,7 @@ class PetApi { /// /// * [Pet] pet (required): /// Pet object that needs to be added to the store - Future addPet(Pet pet,) async { + Future addPet(Pet pet,) async { final response = await addPetWithHttpInfo(pet,); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -70,11 +65,11 @@ class PetApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'Pet',) as Pet; } - return Future.value(); + return null; } /// Deletes a pet @@ -87,18 +82,13 @@ class PetApi { /// Pet id to delete /// /// * [String] apiKey: - Future deletePetWithHttpInfo(int petId, { String apiKey, }) async { - // Verify required params are set. - if (petId == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: petId'); - } - + Future deletePetWithHttpInfo(int petId, { String? apiKey, }) async { // ignore: prefer_const_declarations final path = r'/pet/{petId}' .replaceAll('{petId}', petId.toString()); // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; @@ -119,7 +109,7 @@ class PetApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -132,7 +122,7 @@ class PetApi { /// Pet id to delete /// /// * [String] apiKey: - Future deletePet(int petId, { String apiKey, }) async { + Future deletePet(int petId, { String? apiKey, }) async { final response = await deletePetWithHttpInfo(petId, apiKey: apiKey, ); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -150,22 +140,17 @@ class PetApi { /// * [List] status (required): /// Status values that need to be considered for filter Future findPetsByStatusWithHttpInfo(List status,) async { - // Verify required params are set. - if (status == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: status'); - } - // ignore: prefer_const_declarations final path = r'/pet/findByStatus'; // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; final formParams = {}; - queryParams.addAll(_convertParametersForCollectionFormat('csv', 'status', status)); + queryParams.addAll(_queryParams('csv', 'status', status)); const authNames = ['petstore_auth']; const contentTypes = []; @@ -178,7 +163,7 @@ class PetApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -191,7 +176,7 @@ class PetApi { /// /// * [List] status (required): /// Status values that need to be considered for filter - Future> findPetsByStatus(List status,) async { + Future?> findPetsByStatus(List status,) async { final response = await findPetsByStatusWithHttpInfo(status,); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -199,14 +184,14 @@ class PetApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { final responseBody = await _decodeBodyBytes(response); return (await apiClient.deserializeAsync(responseBody, 'List') as List) .cast() - .toList(growable: false); + .toList(); } - return Future>.value(); + return null; } /// Finds Pets by tags @@ -220,22 +205,17 @@ class PetApi { /// * [List] tags (required): /// Tags to filter by Future findPetsByTagsWithHttpInfo(List tags,) async { - // Verify required params are set. - if (tags == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: tags'); - } - // ignore: prefer_const_declarations final path = r'/pet/findByTags'; // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; final formParams = {}; - queryParams.addAll(_convertParametersForCollectionFormat('csv', 'tags', tags)); + queryParams.addAll(_queryParams('csv', 'tags', tags)); const authNames = ['petstore_auth']; const contentTypes = []; @@ -248,7 +228,7 @@ class PetApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -261,7 +241,7 @@ class PetApi { /// /// * [List] tags (required): /// Tags to filter by - Future> findPetsByTags(List tags,) async { + Future?> findPetsByTags(List tags,) async { final response = await findPetsByTagsWithHttpInfo(tags,); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -269,14 +249,14 @@ class PetApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { final responseBody = await _decodeBodyBytes(response); return (await apiClient.deserializeAsync(responseBody, 'List') as List) .cast() - .toList(growable: false); + .toList(); } - return Future>.value(); + return null; } /// Find pet by ID @@ -290,17 +270,12 @@ class PetApi { /// * [int] petId (required): /// ID of pet to return Future getPetByIdWithHttpInfo(int petId,) async { - // Verify required params are set. - if (petId == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: petId'); - } - // ignore: prefer_const_declarations final path = r'/pet/{petId}' .replaceAll('{petId}', petId.toString()); // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; @@ -317,7 +292,7 @@ class PetApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -330,7 +305,7 @@ class PetApi { /// /// * [int] petId (required): /// ID of pet to return - Future getPetById(int petId,) async { + Future getPetById(int petId,) async { final response = await getPetByIdWithHttpInfo(petId,); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -338,11 +313,11 @@ class PetApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'Pet',) as Pet; } - return Future.value(); + return null; } /// Update an existing pet @@ -354,16 +329,11 @@ class PetApi { /// * [Pet] pet (required): /// Pet object that needs to be added to the store Future updatePetWithHttpInfo(Pet pet,) async { - // Verify required params are set. - if (pet == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: pet'); - } - // ignore: prefer_const_declarations final path = r'/pet'; // ignore: prefer_final_locals - Object postBody = pet; + Object? postBody = pet; final queryParams = []; final headerParams = {}; @@ -380,7 +350,7 @@ class PetApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -391,7 +361,7 @@ class PetApi { /// /// * [Pet] pet (required): /// Pet object that needs to be added to the store - Future updatePet(Pet pet,) async { + Future updatePet(Pet pet,) async { final response = await updatePetWithHttpInfo(pet,); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -399,11 +369,11 @@ class PetApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'Pet',) as Pet; } - return Future.value(); + return null; } /// Updates a pet in the store with form data @@ -420,18 +390,13 @@ class PetApi { /// /// * [String] status: /// Updated status of the pet - Future updatePetWithFormWithHttpInfo(int petId, { String name, String status, }) async { - // Verify required params are set. - if (petId == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: petId'); - } - + Future updatePetWithFormWithHttpInfo(int petId, { String? name, String? status, }) async { // ignore: prefer_const_declarations final path = r'/pet/{petId}' .replaceAll('{petId}', petId.toString()); // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; @@ -454,7 +419,7 @@ class PetApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -471,7 +436,7 @@ class PetApi { /// /// * [String] status: /// Updated status of the pet - Future updatePetWithForm(int petId, { String name, String status, }) async { + Future updatePetWithForm(int petId, { String? name, String? status, }) async { final response = await updatePetWithFormWithHttpInfo(petId, name: name, status: status, ); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -492,18 +457,13 @@ class PetApi { /// /// * [MultipartFile] file: /// file to upload - Future uploadFileWithHttpInfo(int petId, { String additionalMetadata, MultipartFile file, }) async { - // Verify required params are set. - if (petId == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: petId'); - } - + Future uploadFileWithHttpInfo(int petId, { String? additionalMetadata, MultipartFile? file, }) async { // ignore: prefer_const_declarations final path = r'/pet/{petId}/uploadImage' .replaceAll('{petId}', petId.toString()); // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; @@ -534,7 +494,7 @@ class PetApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -551,7 +511,7 @@ class PetApi { /// /// * [MultipartFile] file: /// file to upload - Future uploadFile(int petId, { String additionalMetadata, MultipartFile file, }) async { + Future uploadFile(int petId, { String? additionalMetadata, MultipartFile? file, }) async { final response = await uploadFileWithHttpInfo(petId, additionalMetadata: additionalMetadata, file: file, ); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -559,10 +519,10 @@ class PetApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'ApiResponse',) as ApiResponse; } - return Future.value(); + return null; } } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/store_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/store_api.dart index 0c5c49a95541..dff1442125db 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/store_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/store_api.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -12,7 +12,7 @@ part of openapi.api; class StoreApi { - StoreApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; + StoreApi([ApiClient? apiClient]) : apiClient = apiClient ?? defaultApiClient; final ApiClient apiClient; @@ -27,17 +27,12 @@ class StoreApi { /// * [String] orderId (required): /// ID of the order that needs to be deleted Future deleteOrderWithHttpInfo(String orderId,) async { - // Verify required params are set. - if (orderId == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: orderId'); - } - // ignore: prefer_const_declarations final path = r'/store/order/{orderId}' .replaceAll('{orderId}', orderId); // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; @@ -54,7 +49,7 @@ class StoreApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -84,7 +79,7 @@ class StoreApi { final path = r'/store/inventory'; // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; @@ -101,7 +96,7 @@ class StoreApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -109,7 +104,7 @@ class StoreApi { /// Returns pet inventories by status /// /// Returns a map of status codes to quantities - Future> getInventory() async { + Future?> getInventory() async { final response = await getInventoryWithHttpInfo(); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -117,11 +112,11 @@ class StoreApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return Map.from(await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'Map'),); } - return Future>.value(); + return null; } /// Find purchase order by ID @@ -135,17 +130,12 @@ class StoreApi { /// * [int] orderId (required): /// ID of pet that needs to be fetched Future getOrderByIdWithHttpInfo(int orderId,) async { - // Verify required params are set. - if (orderId == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: orderId'); - } - // ignore: prefer_const_declarations final path = r'/store/order/{orderId}' .replaceAll('{orderId}', orderId.toString()); // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; @@ -162,7 +152,7 @@ class StoreApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -175,7 +165,7 @@ class StoreApi { /// /// * [int] orderId (required): /// ID of pet that needs to be fetched - Future getOrderById(int orderId,) async { + Future getOrderById(int orderId,) async { final response = await getOrderByIdWithHttpInfo(orderId,); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -183,11 +173,11 @@ class StoreApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'Order',) as Order; } - return Future.value(); + return null; } /// Place an order for a pet @@ -199,16 +189,11 @@ class StoreApi { /// * [Order] order (required): /// order placed for purchasing the pet Future placeOrderWithHttpInfo(Order order,) async { - // Verify required params are set. - if (order == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: order'); - } - // ignore: prefer_const_declarations final path = r'/store/order'; // ignore: prefer_final_locals - Object postBody = order; + Object? postBody = order; final queryParams = []; final headerParams = {}; @@ -225,7 +210,7 @@ class StoreApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -236,7 +221,7 @@ class StoreApi { /// /// * [Order] order (required): /// order placed for purchasing the pet - Future placeOrder(Order order,) async { + Future placeOrder(Order order,) async { final response = await placeOrderWithHttpInfo(order,); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -244,10 +229,10 @@ class StoreApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'Order',) as Order; } - return Future.value(); + return null; } } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/user_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/user_api.dart index 3d30943890f1..a479e0b1dd32 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/user_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/user_api.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -12,7 +12,7 @@ part of openapi.api; class UserApi { - UserApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; + UserApi([ApiClient? apiClient]) : apiClient = apiClient ?? defaultApiClient; final ApiClient apiClient; @@ -27,16 +27,11 @@ class UserApi { /// * [User] user (required): /// Created user object Future createUserWithHttpInfo(User user,) async { - // Verify required params are set. - if (user == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: user'); - } - // ignore: prefer_const_declarations final path = r'/user'; // ignore: prefer_final_locals - Object postBody = user; + Object? postBody = user; final queryParams = []; final headerParams = {}; @@ -53,7 +48,7 @@ class UserApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -82,16 +77,11 @@ class UserApi { /// * [List] user (required): /// List of user object Future createUsersWithArrayInputWithHttpInfo(List user,) async { - // Verify required params are set. - if (user == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: user'); - } - // ignore: prefer_const_declarations final path = r'/user/createWithArray'; // ignore: prefer_final_locals - Object postBody = user; + Object? postBody = user; final queryParams = []; final headerParams = {}; @@ -108,7 +98,7 @@ class UserApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -135,16 +125,11 @@ class UserApi { /// * [List] user (required): /// List of user object Future createUsersWithListInputWithHttpInfo(List user,) async { - // Verify required params are set. - if (user == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: user'); - } - // ignore: prefer_const_declarations final path = r'/user/createWithList'; // ignore: prefer_final_locals - Object postBody = user; + Object? postBody = user; final queryParams = []; final headerParams = {}; @@ -161,7 +146,7 @@ class UserApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -190,17 +175,12 @@ class UserApi { /// * [String] username (required): /// The name that needs to be deleted Future deleteUserWithHttpInfo(String username,) async { - // Verify required params are set. - if (username == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: username'); - } - // ignore: prefer_const_declarations final path = r'/user/{username}' .replaceAll('{username}', username); // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; @@ -217,7 +197,7 @@ class UserApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -246,17 +226,12 @@ class UserApi { /// * [String] username (required): /// The name that needs to be fetched. Use user1 for testing. Future getUserByNameWithHttpInfo(String username,) async { - // Verify required params are set. - if (username == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: username'); - } - // ignore: prefer_const_declarations final path = r'/user/{username}' .replaceAll('{username}', username); // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; @@ -273,7 +248,7 @@ class UserApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -284,7 +259,7 @@ class UserApi { /// /// * [String] username (required): /// The name that needs to be fetched. Use user1 for testing. - Future getUserByName(String username,) async { + Future getUserByName(String username,) async { final response = await getUserByNameWithHttpInfo(username,); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -292,11 +267,11 @@ class UserApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'User',) as User; } - return Future.value(); + return null; } /// Logs user into the system @@ -311,26 +286,18 @@ class UserApi { /// * [String] password (required): /// The password for login in clear text Future loginUserWithHttpInfo(String username, String password,) async { - // Verify required params are set. - if (username == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: username'); - } - if (password == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: password'); - } - // ignore: prefer_const_declarations final path = r'/user/login'; // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; final formParams = {}; - queryParams.addAll(_convertParametersForCollectionFormat('', 'username', username)); - queryParams.addAll(_convertParametersForCollectionFormat('', 'password', password)); + queryParams.addAll(_queryParams('', 'username', username)); + queryParams.addAll(_queryParams('', 'password', password)); const authNames = []; const contentTypes = []; @@ -343,7 +310,7 @@ class UserApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -357,7 +324,7 @@ class UserApi { /// /// * [String] password (required): /// The password for login in clear text - Future loginUser(String username, String password,) async { + Future loginUser(String username, String password,) async { final response = await loginUserWithHttpInfo(username, password,); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -365,11 +332,11 @@ class UserApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'String',) as String; } - return Future.value(); + return null; } /// Logs out current logged in user session @@ -380,7 +347,7 @@ class UserApi { final path = r'/user/logout'; // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; @@ -397,7 +364,7 @@ class UserApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -424,20 +391,12 @@ class UserApi { /// * [User] user (required): /// Updated user object Future updateUserWithHttpInfo(String username, User user,) async { - // Verify required params are set. - if (username == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: username'); - } - if (user == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: user'); - } - // ignore: prefer_const_declarations final path = r'/user/{username}' .replaceAll('{username}', username); // ignore: prefer_final_locals - Object postBody = user; + Object? postBody = user; final queryParams = []; final headerParams = {}; @@ -454,7 +413,7 @@ class UserApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_client.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_client.dart index 93057a79a7bf..3efae0775a54 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_client.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_client.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -27,12 +27,7 @@ class ApiClient { Client get client => _client; /// Requests to use a new HTTP [Client] in this class. - /// - /// If the [newClient] is null, an [ArgumentError] is thrown. set client(Client newClient) { - if (newClient == null) { - throw ArgumentError('New client instance cannot be null.'); - } _client = newClient; } @@ -49,7 +44,7 @@ class ApiClient { /// or deleted. Map get authentications => Map.unmodifiable(_authentications); - T getAuthentication(String name) { + T? getAuthentication(String name) { final authentication = _authentications[name]; return authentication is T ? authentication : null; } @@ -60,35 +55,28 @@ class ApiClient { String path, String method, List queryParams, - Object body, + Object? body, Map headerParams, Map formParams, - String nullableContentType, + String? contentType, List authNames, ) async { _updateParamsForAuth(authNames, queryParams, headerParams); headerParams.addAll(_defaultHeaderMap); + if (contentType != null) { + headerParams['Content-Type'] = contentType; + } - final urlEncodedQueryParams = queryParams - .where((param) => param.value != null) - .map((param) => '$param'); - - final queryString = urlEncodedQueryParams.isNotEmpty - ? '?${urlEncodedQueryParams.join('&')}' - : ''; - + final urlEncodedQueryParams = queryParams.map((param) => '$param'); + final queryString = urlEncodedQueryParams.isNotEmpty ? '?${urlEncodedQueryParams.join('&')}' : ''; final uri = Uri.parse('$basePath$path$queryString'); - if (nullableContentType != null) { - headerParams['Content-Type'] = nullableContentType; - } - try { // Special case for uploading a single file which isn't a 'multipart/form-data'. if ( - body is MultipartFile && (nullableContentType == null || - !nullableContentType.toLowerCase().startsWith('multipart/form-data')) + body is MultipartFile && (contentType == null || + !contentType.toLowerCase().startsWith('multipart/form-data')) ) { final request = StreamedRequest(method, uri); request.headers.addAll(headerParams); @@ -114,7 +102,7 @@ class ApiClient { return Response.fromStream(response); } - final msgBody = nullableContentType == 'application/x-www-form-urlencoded' + final msgBody = contentType == 'application/x-www-form-urlencoded' ? formParams : await serializeAsync(body); final nullableHeaderParams = headerParams.isEmpty ? null : headerParams; @@ -127,41 +115,69 @@ class ApiClient { case 'HEAD': return await _client.head(uri, headers: nullableHeaderParams,); case 'GET': return await _client.get(uri, headers: nullableHeaderParams,); } - } on SocketException catch (e, trace) { - throw ApiException.withInner(HttpStatus.badRequest, 'Socket operation failed: $method $path', e, trace,); - } on TlsException catch (e, trace) { - throw ApiException.withInner(HttpStatus.badRequest, 'TLS/SSL communication failed: $method $path', e, trace,); - } on IOException catch (e, trace) { - throw ApiException.withInner(HttpStatus.badRequest, 'I/O operation failed: $method $path', e, trace,); - } on ClientException catch (e, trace) { - throw ApiException.withInner(HttpStatus.badRequest, 'HTTP connection failed: $method $path', e, trace,); - } on Exception catch (e, trace) { - throw ApiException.withInner(HttpStatus.badRequest, 'Exception occurred: $method $path', e, trace,); + } on SocketException catch (error, trace) { + throw ApiException.withInner( + HttpStatus.badRequest, + 'Socket operation failed: $method $path', + error, + trace, + ); + } on TlsException catch (error, trace) { + throw ApiException.withInner( + HttpStatus.badRequest, + 'TLS/SSL communication failed: $method $path', + error, + trace, + ); + } on IOException catch (error, trace) { + throw ApiException.withInner( + HttpStatus.badRequest, + 'I/O operation failed: $method $path', + error, + trace, + ); + } on ClientException catch (error, trace) { + throw ApiException.withInner( + HttpStatus.badRequest, + 'HTTP connection failed: $method $path', + error, + trace, + ); + } on Exception catch (error, trace) { + throw ApiException.withInner( + HttpStatus.badRequest, + 'Exception occurred: $method $path', + error, + trace, + ); } - throw ApiException(HttpStatus.badRequest, 'Invalid HTTP operation: $method $path',); + throw ApiException( + HttpStatus.badRequest, + 'Invalid HTTP operation: $method $path', + ); } - Future deserializeAsync(String json, String targetType, {bool growable}) async => + Future deserializeAsync(String json, String targetType, {bool growable = false,}) async => // ignore: deprecated_member_use_from_same_package deserialize(json, targetType, growable: growable); @Deprecated('Scheduled for removal in OpenAPI Generator 6.x. Use deserializeAsync() instead.') - dynamic deserialize(String json, String targetType, {bool growable}) { + dynamic deserialize(String json, String targetType, {bool growable = false,}) { // Remove all spaces. Necessary for regular expressions as well. targetType = targetType.replaceAll(' ', ''); // ignore: parameter_assignments // If the expected target type is String, nothing to do... return targetType == 'String' ? json - : _deserialize(jsonDecode(json), targetType, growable: growable == true); + : _deserialize(jsonDecode(json), targetType, growable: growable); } // ignore: deprecated_member_use_from_same_package - Future serializeAsync(Object value) async => serialize(value); + Future serializeAsync(Object? value) async => serialize(value); @Deprecated('Scheduled for removal in OpenAPI Generator 6.x. Use serializeAsync() instead.') - String serialize(Object value) => value == null ? '' : json.encode(value); + String serialize(Object? value) => value == null ? '' : json.encode(value); /// Update query and header parameters based on authentication settings. /// @param authNames The authentications to apply @@ -179,7 +195,7 @@ class ApiClient { } } - static dynamic _deserialize(dynamic value, String targetType, {bool growable}) { + static dynamic _deserialize(dynamic value, String targetType, {bool growable = false}) { try { switch (targetType) { case 'String': @@ -207,24 +223,21 @@ class ApiClient { case 'User': return User.fromJson(value); default: - Match match; - if (value is List && (match = _regList.firstMatch(targetType)) != null) { - targetType = match[1]; // ignore: parameter_assignments + dynamic match; + if (value is List && (match = _regList.firstMatch(targetType)?.group(1)) != null) { return value - .map((dynamic v) => _deserialize(v, targetType, growable: growable)) + .map((dynamic v) => _deserialize(v, match, growable: growable,)) .toList(growable: growable); } - if (value is Set && (match = _regSet.firstMatch(targetType)) != null) { - targetType = match[1]; // ignore: parameter_assignments + if (value is Set && (match = _regSet.firstMatch(targetType)?.group(1)) != null) { return value - .map((dynamic v) => _deserialize(v, targetType, growable: growable)) + .map((dynamic v) => _deserialize(v, match, growable: growable,)) .toSet(); } - if (value is Map && (match = _regMap.firstMatch(targetType)) != null) { - targetType = match[1]; // ignore: parameter_assignments + if (value is Map && (match = _regMap.firstMatch(targetType)?.group(1)) != null) { return Map.fromIterables( value.keys.cast(), - value.values.map((dynamic v) => _deserialize(v, targetType, growable: growable)), + value.values.map((dynamic v) => _deserialize(v, match, growable: growable,)), ); } } @@ -238,9 +251,9 @@ class ApiClient { /// Primarily intended for use in an isolate. class DeserializationMessage { const DeserializationMessage({ - @required this.json, - @required this.targetType, - this.growable, + required this.json, + required this.targetType, + this.growable = false, }); /// The JSON value to deserialize. @@ -264,9 +277,9 @@ Future deserializeAsync(DeserializationMessage message) async { : ApiClient._deserialize( jsonDecode(message.json), targetType, - growable: message.growable == true, + growable: message.growable, ); } /// Primarily intended for use in an isolate. -Future serializeAsync(Object value) async => value == null ? '' : json.encode(value); +Future serializeAsync(Object? value) async => value == null ? '' : json.encode(value); diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_exception.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_exception.dart index 8ffc340b4c9d..796f7f7ee74e 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_exception.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_exception.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -16,9 +16,9 @@ class ApiException implements Exception { ApiException.withInner(this.code, this.message, this.innerException, this.stackTrace); int code = 0; - String message; - Exception innerException; - StackTrace stackTrace; + String? message; + Exception? innerException; + StackTrace? stackTrace; @override String toString() { diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_helper.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_helper.dart index cf97058bec28..d6adb1798250 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_helper.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_helper.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -21,32 +21,27 @@ class QueryParam { } // Ported from the Java version. -Iterable _convertParametersForCollectionFormat( - String collectionFormat, - String name, - dynamic value, -) { +Iterable _queryParams(String collectionFormat, String name, dynamic value,) { + // Assertions to run in debug mode only. + assert(name.isNotEmpty, 'Parameter cannot be an empty string.'); + final params = []; - // preconditions - if (name != null && name.isNotEmpty && value != null) { - if (value is List) { - if (collectionFormat == 'multi') { - return value.map((dynamic v) => QueryParam(name, parameterToString(v)),); - } + if (value is List) { + if (collectionFormat == 'multi') { + return value.map((dynamic v) => QueryParam(name, parameterToString(v)),); + } - // Default collection format is 'csv'. - if (collectionFormat == null || collectionFormat.isEmpty) { - // ignore: parameter_assignments - collectionFormat = 'csv'; - } + // Default collection format is 'csv'. + if (collectionFormat.isEmpty) { + collectionFormat = 'csv'; // ignore: parameter_assignments + } - final delimiter = _delimiters[collectionFormat] ?? ','; + final delimiter = _delimiters[collectionFormat] ?? ','; - params.add(QueryParam(name, value.map(parameterToString).join(delimiter)),); - } else { - params.add(QueryParam(name, parameterToString(value),)); - } + params.add(QueryParam(name, value.map(parameterToString).join(delimiter),)); + } else if (value != null) { + params.add(QueryParam(name, parameterToString(value))); } return params; @@ -68,27 +63,27 @@ String parameterToString(dynamic value) { Future _decodeBodyBytes(Response response) async { final contentType = response.headers['content-type']; return contentType != null && contentType.toLowerCase().startsWith('application/json') - ? response.bodyBytes == null ? null : utf8.decode(response.bodyBytes) + ? response.bodyBytes.isEmpty ? '' : utf8.decode(response.bodyBytes) : response.body; } /// Returns a valid [T] value found at the specified Map [key], null otherwise. -T mapValueOfType(dynamic map, String key) { +T? mapValueOfType(dynamic map, String key) { final dynamic value = map is Map ? map[key] : null; return value is T ? value : null; } /// Returns a valid Map found at the specified Map [key], null otherwise. -Map mapCastOfType(dynamic map, String key) { +Map? mapCastOfType(dynamic map, String key) { final dynamic value = map is Map ? map[key] : null; return value is Map ? value.cast() : null; } /// Returns a valid [DateTime] found at the specified Map [key], null otherwise. -DateTime mapDateTime(dynamic map, String key, [String pattern]) { +DateTime? mapDateTime(dynamic map, String key, [String? pattern]) { final dynamic value = map is Map ? map[key] : null; if (value != null) { - int millis; + int? millis; if (value is int) { millis = value; } else if (value is String) { diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/api_key_auth.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/api_key_auth.dart index 0c2303af09e9..e304eda321ee 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/api_key_auth.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/api_key_auth.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -16,23 +16,25 @@ class ApiKeyAuth implements Authentication { final String location; final String paramName; - String apiKeyPrefix; - String apiKey; + String apiKeyPrefix = ''; + String apiKey = ''; @override void applyToParams(List queryParams, Map headerParams) { - final value = apiKeyPrefix == null ? apiKey : '$apiKeyPrefix $apiKey'; + final paramValue = apiKeyPrefix.isEmpty ? apiKey : '$apiKeyPrefix $apiKey'; - if (location == 'query' && value != null) { - queryParams.add(QueryParam(paramName, value)); - } else if (location == 'header' && value != null) { - headerParams[paramName] = value; - } else if (location == 'cookie' && value != null) { - headerParams.update( - 'Cookie', - (existingCookie) => '$existingCookie; $paramName=$value', - ifAbsent: () => '$paramName=$value', - ); + if (paramValue.isNotEmpty) { + if (location == 'query') { + queryParams.add(QueryParam(paramName, paramValue)); + } else if (location == 'header') { + headerParams[paramName] = paramValue; + } else if (location == 'cookie') { + headerParams.update( + 'Cookie', + (existingCookie) => '$existingCookie; $paramName=$paramValue', + ifAbsent: () => '$paramName=$paramValue', + ); + } } } } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/authentication.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/authentication.dart index 4257e1900069..49baf7c46a9c 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/authentication.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/authentication.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/http_basic_auth.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/http_basic_auth.dart index 0494f402d958..81abd7185f2d 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/http_basic_auth.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/http_basic_auth.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -11,12 +11,16 @@ part of openapi.api; class HttpBasicAuth implements Authentication { + HttpBasicAuth({this.username = '', this.password = ''}); + String username; String password; @override void applyToParams(List queryParams, Map headerParams) { - final credentials = '${username ?? ''}:${password ?? ''}'; - headerParams['Authorization'] = 'Basic ${base64.encode(utf8.encode(credentials))}'; + if (username.isNotEmpty && password.isNotEmpty) { + final credentials = '$username:$password'; + headerParams['Authorization'] = 'Basic ${base64.encode(utf8.encode(credentials))}'; + } } } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/http_bearer_auth.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/http_bearer_auth.dart index 23e243523dd8..213f3483b8fb 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/http_bearer_auth.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/http_bearer_auth.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -21,19 +21,29 @@ class HttpBearerAuth implements Authentication { set accessToken(dynamic accessToken) { if (accessToken is! String && accessToken is! HttpBearerAuthProvider) { - throw ArgumentError('Type of Bearer accessToken should be a String or a String Function().'); + throw ArgumentError('accessToken value must be either a String or a String Function().'); } _accessToken = accessToken; } @override void applyToParams(List queryParams, Map headerParams) { + if (_accessToken == null) { + return; + } + + String accessToken; + if (_accessToken is String) { - headerParams['Authorization'] = 'Bearer $_accessToken'; + accessToken = _accessToken; } else if (_accessToken is HttpBearerAuthProvider) { - headerParams['Authorization'] = 'Bearer ${_accessToken()}'; + accessToken = _accessToken!(); } else { - throw ArgumentError('Type of Bearer accessToken should be a String or a String Function().'); + return; + } + + if (accessToken.isNotEmpty) { + headerParams['Authorization'] = 'Bearer $accessToken'; } } } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/oauth.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/oauth.dart index 9299ac13f5bf..e9b87cffb052 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/oauth.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/oauth.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -11,13 +11,13 @@ part of openapi.api; class OAuth implements Authentication { - OAuth({this.accessToken}); + OAuth({this.accessToken = ''}); String accessToken; @override void applyToParams(List queryParams, Map headerParams) { - if (accessToken != null) { + if (accessToken.isNotEmpty) { headerParams['Authorization'] = 'Bearer $accessToken'; } } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/api_response.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/api_response.dart index bfd43366211f..6042baea5514 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/api_response.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/api_response.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -18,11 +18,29 @@ class ApiResponse { this.message, }); - int code; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? code; - String type; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? type; - String message; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? message; @override bool operator ==(Object other) => identical(this, other) || other is ApiResponse && @@ -32,10 +50,10 @@ class ApiResponse { @override int get hashCode => - // ignore: unnecessary_parenthesis - (code == null ? 0 : code.hashCode) + - (type == null ? 0 : type.hashCode) + - (message == null ? 0 : message.hashCode); + // ignore: unnecessary_parenthesis + (code == null ? 0 : code!.hashCode) + + (type == null ? 0 : type!.hashCode) + + (message == null ? 0 : message!.hashCode); @override String toString() => 'ApiResponse[code=$code, type=$type, message=$message]'; @@ -57,9 +75,21 @@ class ApiResponse { /// Returns a new [ApiResponse] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static ApiResponse fromJson(dynamic value) { + static ApiResponse? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "ApiResponse[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "ApiResponse[$key]" has a null value in JSON.'); + }); + return true; + }()); + return ApiResponse( code: mapValueOfType(json, r'code'), type: mapValueOfType(json, r'type'), @@ -69,36 +99,50 @@ class ApiResponse { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(ApiResponse.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = ApiResponse.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = ApiResponse.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = ApiResponse.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of ApiResponse-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = ApiResponse.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = ApiResponse.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/category.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/category.dart index 50ad28ee0069..f4a572dffc73 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/category.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/category.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -17,9 +17,21 @@ class Category { this.name, }); - int id; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? id; - String name; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? name; @override bool operator ==(Object other) => identical(this, other) || other is Category && @@ -28,9 +40,9 @@ class Category { @override int get hashCode => - // ignore: unnecessary_parenthesis - (id == null ? 0 : id.hashCode) + - (name == null ? 0 : name.hashCode); + // ignore: unnecessary_parenthesis + (id == null ? 0 : id!.hashCode) + + (name == null ? 0 : name!.hashCode); @override String toString() => 'Category[id=$id, name=$name]'; @@ -49,9 +61,21 @@ class Category { /// Returns a new [Category] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static Category fromJson(dynamic value) { + static Category? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "Category[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "Category[$key]" has a null value in JSON.'); + }); + return true; + }()); + return Category( id: mapValueOfType(json, r'id'), name: mapValueOfType(json, r'name'), @@ -60,36 +84,50 @@ class Category { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(Category.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = Category.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = Category.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Category.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of Category-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = Category.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Category.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/order.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/order.dart index 61d01acfaaa8..ad84a894e8db 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/order.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/order.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -21,16 +21,40 @@ class Order { this.complete = false, }); - int id; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? id; - int petId; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? petId; - int quantity; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? quantity; - DateTime shipDate; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + DateTime? shipDate; /// Order Status - OrderStatusEnum status; + OrderStatusEnum? status; bool complete; @@ -45,13 +69,13 @@ class Order { @override int get hashCode => - // ignore: unnecessary_parenthesis - (id == null ? 0 : id.hashCode) + - (petId == null ? 0 : petId.hashCode) + - (quantity == null ? 0 : quantity.hashCode) + - (shipDate == null ? 0 : shipDate.hashCode) + - (status == null ? 0 : status.hashCode) + - (complete == null ? 0 : complete.hashCode); + // ignore: unnecessary_parenthesis + (id == null ? 0 : id!.hashCode) + + (petId == null ? 0 : petId!.hashCode) + + (quantity == null ? 0 : quantity!.hashCode) + + (shipDate == null ? 0 : shipDate!.hashCode) + + (status == null ? 0 : status!.hashCode) + + (complete.hashCode); @override String toString() => 'Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete]'; @@ -68,66 +92,90 @@ class Order { json[r'quantity'] = quantity; } if (shipDate != null) { - json[r'shipDate'] = shipDate.toUtc().toIso8601String(); + json[r'shipDate'] = shipDate!.toUtc().toIso8601String(); } if (status != null) { json[r'status'] = status; } - if (complete != null) { json[r'complete'] = complete; - } return json; } /// Returns a new [Order] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static Order fromJson(dynamic value) { + static Order? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "Order[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "Order[$key]" has a null value in JSON.'); + }); + return true; + }()); + return Order( id: mapValueOfType(json, r'id'), petId: mapValueOfType(json, r'petId'), quantity: mapValueOfType(json, r'quantity'), shipDate: mapDateTime(json, r'shipDate', ''), status: OrderStatusEnum.fromJson(json[r'status']), - complete: mapValueOfType(json, r'complete'), + complete: mapValueOfType(json, r'complete') ?? false, ); } return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(Order.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = Order.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = Order.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Order.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of Order-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = Order.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Order.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } /// Order Status @@ -139,7 +187,7 @@ class OrderStatusEnum { final String value; @override - String toString() => value ?? ''; + String toString() => value; String toJson() => value; @@ -154,13 +202,20 @@ class OrderStatusEnum { delivered, ]; - static OrderStatusEnum fromJson(dynamic value) => - OrderStatusEnumTypeTransformer().decode(value); + static OrderStatusEnum? fromJson(dynamic value) => OrderStatusEnumTypeTransformer().decode(value); - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(OrderStatusEnum.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = OrderStatusEnum.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } } /// Transformation class that can [encode] an instance of [OrderStatusEnum] to String, @@ -180,14 +235,14 @@ class OrderStatusEnumTypeTransformer { /// /// The [allowNull] is very handy when an API changes and a new enum value is added or removed, /// and users are still using an old app with the old code. - OrderStatusEnum decode(dynamic data, {bool allowNull}) { + OrderStatusEnum? decode(dynamic data, {bool allowNull = true}) { if (data != null) { switch (data.toString()) { case r'placed': return OrderStatusEnum.placed; case r'approved': return OrderStatusEnum.approved; case r'delivered': return OrderStatusEnum.delivered; default: - if (allowNull == false) { + if (!allowNull) { throw ArgumentError('Unknown enum value to decode: $data'); } } @@ -196,7 +251,7 @@ class OrderStatusEnumTypeTransformer { } /// Singleton [OrderStatusEnumTypeTransformer] instance. - static OrderStatusEnumTypeTransformer _instance; + static OrderStatusEnumTypeTransformer? _instance; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/pet.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/pet.dart index 7b8d3c195e7b..62856ddace32 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/pet.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/pet.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -15,15 +15,27 @@ class Pet { Pet({ this.id, this.category, - @required this.name, + required this.name, this.photoUrls = const [], this.tags = const [], this.status, }); - int id; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? id; - Category category; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + Category? category; String name; @@ -32,7 +44,7 @@ class Pet { List tags; /// pet status in the store - PetStatusEnum status; + PetStatusEnum? status; @override bool operator ==(Object other) => identical(this, other) || other is Pet && @@ -45,13 +57,13 @@ class Pet { @override int get hashCode => - // ignore: unnecessary_parenthesis - (id == null ? 0 : id.hashCode) + - (category == null ? 0 : category.hashCode) + - (name == null ? 0 : name.hashCode) + - (photoUrls == null ? 0 : photoUrls.hashCode) + - (tags == null ? 0 : tags.hashCode) + - (status == null ? 0 : status.hashCode); + // ignore: unnecessary_parenthesis + (id == null ? 0 : id!.hashCode) + + (category == null ? 0 : category!.hashCode) + + (name.hashCode) + + (photoUrls.hashCode) + + (tags.hashCode) + + (status == null ? 0 : status!.hashCode); @override String toString() => 'Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$status]'; @@ -66,9 +78,7 @@ class Pet { } json[r'name'] = name; json[r'photoUrls'] = photoUrls; - if (tags != null) { json[r'tags'] = tags; - } if (status != null) { json[r'status'] = status; } @@ -78,54 +88,82 @@ class Pet { /// Returns a new [Pet] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static Pet fromJson(dynamic value) { + static Pet? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "Pet[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "Pet[$key]" has a null value in JSON.'); + }); + return true; + }()); + return Pet( id: mapValueOfType(json, r'id'), category: Category.fromJson(json[r'category']), - name: mapValueOfType(json, r'name'), + name: mapValueOfType(json, r'name')!, photoUrls: json[r'photoUrls'] is List - ? (json[r'photoUrls'] as List).cast() - : null, - tags: Tag.listFromJson(json[r'tags']), + ? (json[r'photoUrls'] as List).cast() + : const [], + tags: Tag.listFromJson(json[r'tags']) ?? const [], status: PetStatusEnum.fromJson(json[r'status']), ); } return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(Pet.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = Pet.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = Pet.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Pet.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of Pet-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = Pet.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Pet.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + 'name', + 'photoUrls', + }; } /// pet status in the store @@ -137,7 +175,7 @@ class PetStatusEnum { final String value; @override - String toString() => value ?? ''; + String toString() => value; String toJson() => value; @@ -152,13 +190,20 @@ class PetStatusEnum { sold, ]; - static PetStatusEnum fromJson(dynamic value) => - PetStatusEnumTypeTransformer().decode(value); + static PetStatusEnum? fromJson(dynamic value) => PetStatusEnumTypeTransformer().decode(value); - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(PetStatusEnum.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = PetStatusEnum.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } } /// Transformation class that can [encode] an instance of [PetStatusEnum] to String, @@ -178,14 +223,14 @@ class PetStatusEnumTypeTransformer { /// /// The [allowNull] is very handy when an API changes and a new enum value is added or removed, /// and users are still using an old app with the old code. - PetStatusEnum decode(dynamic data, {bool allowNull}) { + PetStatusEnum? decode(dynamic data, {bool allowNull = true}) { if (data != null) { switch (data.toString()) { case r'available': return PetStatusEnum.available; case r'pending': return PetStatusEnum.pending; case r'sold': return PetStatusEnum.sold; default: - if (allowNull == false) { + if (!allowNull) { throw ArgumentError('Unknown enum value to decode: $data'); } } @@ -194,7 +239,7 @@ class PetStatusEnumTypeTransformer { } /// Singleton [PetStatusEnumTypeTransformer] instance. - static PetStatusEnumTypeTransformer _instance; + static PetStatusEnumTypeTransformer? _instance; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/tag.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/tag.dart index 193c7004028f..71b8799d1cb1 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/tag.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/tag.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -17,9 +17,21 @@ class Tag { this.name, }); - int id; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? id; - String name; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? name; @override bool operator ==(Object other) => identical(this, other) || other is Tag && @@ -28,9 +40,9 @@ class Tag { @override int get hashCode => - // ignore: unnecessary_parenthesis - (id == null ? 0 : id.hashCode) + - (name == null ? 0 : name.hashCode); + // ignore: unnecessary_parenthesis + (id == null ? 0 : id!.hashCode) + + (name == null ? 0 : name!.hashCode); @override String toString() => 'Tag[id=$id, name=$name]'; @@ -49,9 +61,21 @@ class Tag { /// Returns a new [Tag] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static Tag fromJson(dynamic value) { + static Tag? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "Tag[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "Tag[$key]" has a null value in JSON.'); + }); + return true; + }()); + return Tag( id: mapValueOfType(json, r'id'), name: mapValueOfType(json, r'name'), @@ -60,36 +84,50 @@ class Tag { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(Tag.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = Tag.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = Tag.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Tag.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of Tag-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = Tag.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Tag.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/user.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/user.dart index d2b94ed6a7ab..0b10d4fe7c23 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/user.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/user.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -23,22 +23,70 @@ class User { this.userStatus, }); - int id; - - String username; - - String firstName; - - String lastName; - - String email; - - String password; - - String phone; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? id; + + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? username; + + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? firstName; + + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? lastName; + + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? email; + + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? password; + + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? phone; /// User Status - int userStatus; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? userStatus; @override bool operator ==(Object other) => identical(this, other) || other is User && @@ -53,15 +101,15 @@ class User { @override int get hashCode => - // ignore: unnecessary_parenthesis - (id == null ? 0 : id.hashCode) + - (username == null ? 0 : username.hashCode) + - (firstName == null ? 0 : firstName.hashCode) + - (lastName == null ? 0 : lastName.hashCode) + - (email == null ? 0 : email.hashCode) + - (password == null ? 0 : password.hashCode) + - (phone == null ? 0 : phone.hashCode) + - (userStatus == null ? 0 : userStatus.hashCode); + // ignore: unnecessary_parenthesis + (id == null ? 0 : id!.hashCode) + + (username == null ? 0 : username!.hashCode) + + (firstName == null ? 0 : firstName!.hashCode) + + (lastName == null ? 0 : lastName!.hashCode) + + (email == null ? 0 : email!.hashCode) + + (password == null ? 0 : password!.hashCode) + + (phone == null ? 0 : phone!.hashCode) + + (userStatus == null ? 0 : userStatus!.hashCode); @override String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]'; @@ -98,9 +146,21 @@ class User { /// Returns a new [User] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static User fromJson(dynamic value) { + static User? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "User[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "User[$key]" has a null value in JSON.'); + }); + return true; + }()); + return User( id: mapValueOfType(json, r'id'), username: mapValueOfType(json, r'username'), @@ -115,36 +175,50 @@ class User { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(User.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = User.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = User.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = User.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of User-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = User.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = User.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/api_response_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/api_response_test.dart index b0c30615b926..e9743c1ddded 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/api_response_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/api_response_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for ApiResponse void main() { - final instance = ApiResponse(); + // final instance = ApiResponse(); group('test ApiResponse', () { // int code diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/category_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/category_test.dart index 1849d609ebb2..3e0e90fc90db 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/category_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/category_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for Category void main() { - final instance = Category(); + // final instance = Category(); group('test Category', () { // int id diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/order_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/order_test.dart index 614a14e42bb9..b625abdaf9fc 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/order_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/order_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for Order void main() { - final instance = Order(); + // final instance = Order(); group('test Order', () { // int id diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/pet_api_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/pet_api_test.dart index f143f4905306..bdb430ea1a80 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/pet_api_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/pet_api_test.dart @@ -1,19 +1,21 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 /// tests for PetApi void main() { - final instance = PetApi(); + // final instance = PetApi(); group('tests for PetApi', () { // Add a new pet to the store diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/pet_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/pet_test.dart index a3b16fbd7abd..ddb8f6a569e3 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/pet_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/pet_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for Pet void main() { - final instance = Pet(); + // final instance = Pet(); group('test Pet', () { // int id diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/store_api_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/store_api_test.dart index 4a7ed54abbbc..351ef2682801 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/store_api_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/store_api_test.dart @@ -1,19 +1,21 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 /// tests for StoreApi void main() { - final instance = StoreApi(); + // final instance = StoreApi(); group('tests for StoreApi', () { // Delete purchase order by ID diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/tag_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/tag_test.dart index 66ecdfe488dc..78d5880e6d4c 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/tag_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/tag_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for Tag void main() { - final instance = Tag(); + // final instance = Tag(); group('test Tag', () { // int id diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/user_api_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/user_api_test.dart index 73ee89a29451..4f82364bd172 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/user_api_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/user_api_test.dart @@ -1,19 +1,21 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 /// tests for UserApi void main() { - final instance = UserApi(); + // final instance = UserApi(); group('tests for UserApi', () { // Create user diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/user_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/user_test.dart index b89cd360489d..d86551e10b64 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/user_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/test/user_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for User void main() { - final instance = User(); + // final instance = User(); group('test User', () { // int id diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/.gitignore b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/.gitignore index 8b7331fd822c..1be28ced0940 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/.gitignore +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/.gitignore @@ -1,27 +1,17 @@ -# See https://www.dartlang.org/tools/private-files.html +# See https://dart.dev/guides/libraries/private-files -# Files and directories created by pub -.buildlog +.dart_tool/ .packages -.project -.pub/ build/ -**/packages/ +pubspec.lock # Except for application packages -# Files created by dart2js -# (Most Dart developers will use pub build to compile Dart, use/modify these -# rules if you intend to use dart2js directly -# Convention is to use extension '.dart.js' for Dart compiled to Javascript to -# differentiate from explicit Javascript files) -*.dart.js -*.part.js -*.js.deps -*.js.map -*.info.json - -# Directory created by dartdoc doc/api/ -# Don't commit pubspec lock file -# (Library packages only! Remove pattern if developing an application package) -pubspec.lock +# IntelliJ +*.iml +*.ipr +*.iws +.idea/ + +# Mac +.DS_Store diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/.travis.yml b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/.travis.yml index 1a3af66d54c7..2774ccbba0e9 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/.travis.yml +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/.travis.yml @@ -6,7 +6,7 @@ language: dart dart: # Install a specific stable release -- "2.2.0" +- "2.12" install: - pub get diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/README.md b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/README.md index db2f2c26eac2..408714551412 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/README.md +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/README.md @@ -8,7 +8,7 @@ This Dart package is automatically generated by the [OpenAPI Generator](https:// ## Requirements -Dart 2.0 or later +Dart 2.12 or later ## Installation & Usage diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api.dart index 34d6adae2fa5..48f61a0d5f5d 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/another_fake_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/another_fake_api.dart index 61a4d7786677..f03350c4dfff 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/another_fake_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/another_fake_api.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -12,7 +12,7 @@ part of openapi.api; class AnotherFakeApi { - AnotherFakeApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; + AnotherFakeApi([ApiClient? apiClient]) : apiClient = apiClient ?? defaultApiClient; final ApiClient apiClient; @@ -27,16 +27,11 @@ class AnotherFakeApi { /// * [ModelClient] modelClient (required): /// client model Future call123testSpecialTagsWithHttpInfo(ModelClient modelClient,) async { - // Verify required params are set. - if (modelClient == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: modelClient'); - } - // ignore: prefer_const_declarations final path = r'/another-fake/dummy'; // ignore: prefer_final_locals - Object postBody = modelClient; + Object? postBody = modelClient; final queryParams = []; final headerParams = {}; @@ -53,7 +48,7 @@ class AnotherFakeApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -66,7 +61,7 @@ class AnotherFakeApi { /// /// * [ModelClient] modelClient (required): /// client model - Future call123testSpecialTags(ModelClient modelClient,) async { + Future call123testSpecialTags(ModelClient modelClient,) async { final response = await call123testSpecialTagsWithHttpInfo(modelClient,); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -74,10 +69,10 @@ class AnotherFakeApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'ModelClient',) as ModelClient; } - return Future.value(); + return null; } } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/default_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/default_api.dart index 15119087b633..02c22bfa2d9f 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/default_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/default_api.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -12,7 +12,7 @@ part of openapi.api; class DefaultApi { - DefaultApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; + DefaultApi([ApiClient? apiClient]) : apiClient = apiClient ?? defaultApiClient; final ApiClient apiClient; @@ -22,7 +22,7 @@ class DefaultApi { final path = r'/foo'; // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; @@ -39,12 +39,12 @@ class DefaultApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } - Future fooGet() async { + Future fooGet() async { final response = await fooGetWithHttpInfo(); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -52,10 +52,10 @@ class DefaultApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'InlineResponseDefault',) as InlineResponseDefault; } - return Future.value(); + return null; } } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_api.dart index 5ffad95f3b68..9d260e34f124 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_api.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -12,7 +12,7 @@ part of openapi.api; class FakeApi { - FakeApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; + FakeApi([ApiClient? apiClient]) : apiClient = apiClient ?? defaultApiClient; final ApiClient apiClient; @@ -24,7 +24,7 @@ class FakeApi { final path = r'/fake/health'; // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; @@ -41,13 +41,13 @@ class FakeApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } /// Health check endpoint - Future fakeHealthGet() async { + Future fakeHealthGet() async { final response = await fakeHealthGetWithHttpInfo(); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -55,11 +55,11 @@ class FakeApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'HealthCheckResult',) as HealthCheckResult; } - return Future.value(); + return null; } /// test http signature authentication @@ -76,24 +76,19 @@ class FakeApi { /// /// * [String] header1: /// header parameter - Future fakeHttpSignatureTestWithHttpInfo(Pet pet, { String query1, String header1, }) async { - // Verify required params are set. - if (pet == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: pet'); - } - + Future fakeHttpSignatureTestWithHttpInfo(Pet pet, { String? query1, String? header1, }) async { // ignore: prefer_const_declarations final path = r'/fake/http-signature-test'; // ignore: prefer_final_locals - Object postBody = pet; + Object? postBody = pet; final queryParams = []; final headerParams = {}; final formParams = {}; if (query1 != null) { - queryParams.addAll(_convertParametersForCollectionFormat('', 'query_1', query1)); + queryParams.addAll(_queryParams('', 'query_1', query1)); } if (header1 != null) { @@ -111,7 +106,7 @@ class FakeApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -128,7 +123,7 @@ class FakeApi { /// /// * [String] header1: /// header parameter - Future fakeHttpSignatureTest(Pet pet, { String query1, String header1, }) async { + Future fakeHttpSignatureTest(Pet pet, { String? query1, String? header1, }) async { final response = await fakeHttpSignatureTestWithHttpInfo(pet, query1: query1, header1: header1, ); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -143,14 +138,12 @@ class FakeApi { /// /// * [bool] body: /// Input boolean as post body - Future fakeOuterBooleanSerializeWithHttpInfo({ bool body, }) async { - // Verify required params are set. - + Future fakeOuterBooleanSerializeWithHttpInfo({ bool? body, }) async { // ignore: prefer_const_declarations final path = r'/fake/outer/boolean'; // ignore: prefer_final_locals - Object postBody = body; + Object? postBody = body; final queryParams = []; final headerParams = {}; @@ -167,7 +160,7 @@ class FakeApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -178,7 +171,7 @@ class FakeApi { /// /// * [bool] body: /// Input boolean as post body - Future fakeOuterBooleanSerialize({ bool body, }) async { + Future fakeOuterBooleanSerialize({ bool? body, }) async { final response = await fakeOuterBooleanSerializeWithHttpInfo( body: body, ); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -186,11 +179,11 @@ class FakeApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'bool',) as bool; } - return Future.value(); + return null; } /// Test serialization of object with outer number type @@ -201,14 +194,12 @@ class FakeApi { /// /// * [OuterComposite] outerComposite: /// Input composite as post body - Future fakeOuterCompositeSerializeWithHttpInfo({ OuterComposite outerComposite, }) async { - // Verify required params are set. - + Future fakeOuterCompositeSerializeWithHttpInfo({ OuterComposite? outerComposite, }) async { // ignore: prefer_const_declarations final path = r'/fake/outer/composite'; // ignore: prefer_final_locals - Object postBody = outerComposite; + Object? postBody = outerComposite; final queryParams = []; final headerParams = {}; @@ -225,7 +216,7 @@ class FakeApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -236,7 +227,7 @@ class FakeApi { /// /// * [OuterComposite] outerComposite: /// Input composite as post body - Future fakeOuterCompositeSerialize({ OuterComposite outerComposite, }) async { + Future fakeOuterCompositeSerialize({ OuterComposite? outerComposite, }) async { final response = await fakeOuterCompositeSerializeWithHttpInfo( outerComposite: outerComposite, ); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -244,11 +235,11 @@ class FakeApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'OuterComposite',) as OuterComposite; } - return Future.value(); + return null; } /// Test serialization of outer number types @@ -259,14 +250,12 @@ class FakeApi { /// /// * [num] body: /// Input number as post body - Future fakeOuterNumberSerializeWithHttpInfo({ num body, }) async { - // Verify required params are set. - + Future fakeOuterNumberSerializeWithHttpInfo({ num? body, }) async { // ignore: prefer_const_declarations final path = r'/fake/outer/number'; // ignore: prefer_final_locals - Object postBody = body; + Object? postBody = body; final queryParams = []; final headerParams = {}; @@ -283,7 +272,7 @@ class FakeApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -294,7 +283,7 @@ class FakeApi { /// /// * [num] body: /// Input number as post body - Future fakeOuterNumberSerialize({ num body, }) async { + Future fakeOuterNumberSerialize({ num? body, }) async { final response = await fakeOuterNumberSerializeWithHttpInfo( body: body, ); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -302,11 +291,11 @@ class FakeApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'num',) as num; } - return Future.value(); + return null; } /// Test serialization of outer string types @@ -317,14 +306,12 @@ class FakeApi { /// /// * [String] body: /// Input string as post body - Future fakeOuterStringSerializeWithHttpInfo({ String body, }) async { - // Verify required params are set. - + Future fakeOuterStringSerializeWithHttpInfo({ String? body, }) async { // ignore: prefer_const_declarations final path = r'/fake/outer/string'; // ignore: prefer_final_locals - Object postBody = body; + Object? postBody = body; final queryParams = []; final headerParams = {}; @@ -341,7 +328,7 @@ class FakeApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -352,7 +339,7 @@ class FakeApi { /// /// * [String] body: /// Input string as post body - Future fakeOuterStringSerialize({ String body, }) async { + Future fakeOuterStringSerialize({ String? body, }) async { final response = await fakeOuterStringSerializeWithHttpInfo( body: body, ); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -360,11 +347,11 @@ class FakeApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'String',) as String; } - return Future.value(); + return null; } /// Test serialization of enum (int) properties with examples @@ -376,16 +363,11 @@ class FakeApi { /// * [OuterObjectWithEnumProperty] outerObjectWithEnumProperty (required): /// Input enum (int) as post body Future fakePropertyEnumIntegerSerializeWithHttpInfo(OuterObjectWithEnumProperty outerObjectWithEnumProperty,) async { - // Verify required params are set. - if (outerObjectWithEnumProperty == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: outerObjectWithEnumProperty'); - } - // ignore: prefer_const_declarations final path = r'/fake/property/enum-int'; // ignore: prefer_final_locals - Object postBody = outerObjectWithEnumProperty; + Object? postBody = outerObjectWithEnumProperty; final queryParams = []; final headerParams = {}; @@ -402,7 +384,7 @@ class FakeApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -413,7 +395,7 @@ class FakeApi { /// /// * [OuterObjectWithEnumProperty] outerObjectWithEnumProperty (required): /// Input enum (int) as post body - Future fakePropertyEnumIntegerSerialize(OuterObjectWithEnumProperty outerObjectWithEnumProperty,) async { + Future fakePropertyEnumIntegerSerialize(OuterObjectWithEnumProperty outerObjectWithEnumProperty,) async { final response = await fakePropertyEnumIntegerSerializeWithHttpInfo(outerObjectWithEnumProperty,); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -421,11 +403,11 @@ class FakeApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'OuterObjectWithEnumProperty',) as OuterObjectWithEnumProperty; } - return Future.value(); + return null; } /// For this test, the body has to be a binary file. @@ -437,16 +419,11 @@ class FakeApi { /// * [MultipartFile] body (required): /// image to upload Future testBodyWithBinaryWithHttpInfo(MultipartFile body,) async { - // Verify required params are set. - if (body == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: body'); - } - // ignore: prefer_const_declarations final path = r'/fake/body-with-binary'; // ignore: prefer_final_locals - Object postBody = body; + Object? postBody = body; final queryParams = []; final headerParams = {}; @@ -463,7 +440,7 @@ class FakeApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -489,16 +466,11 @@ class FakeApi { /// /// * [FileSchemaTestClass] fileSchemaTestClass (required): Future testBodyWithFileSchemaWithHttpInfo(FileSchemaTestClass fileSchemaTestClass,) async { - // Verify required params are set. - if (fileSchemaTestClass == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: fileSchemaTestClass'); - } - // ignore: prefer_const_declarations final path = r'/fake/body-with-file-schema'; // ignore: prefer_final_locals - Object postBody = fileSchemaTestClass; + Object? postBody = fileSchemaTestClass; final queryParams = []; final headerParams = {}; @@ -515,7 +487,7 @@ class FakeApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -539,25 +511,17 @@ class FakeApi { /// /// * [User] user (required): Future testBodyWithQueryParamsWithHttpInfo(String query, User user,) async { - // Verify required params are set. - if (query == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: query'); - } - if (user == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: user'); - } - // ignore: prefer_const_declarations final path = r'/fake/body-with-query-params'; // ignore: prefer_final_locals - Object postBody = user; + Object? postBody = user; final queryParams = []; final headerParams = {}; final formParams = {}; - queryParams.addAll(_convertParametersForCollectionFormat('', 'query', query)); + queryParams.addAll(_queryParams('', 'query', query)); const authNames = []; const contentTypes = ['application/json']; @@ -570,7 +534,7 @@ class FakeApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -598,16 +562,11 @@ class FakeApi { /// * [ModelClient] modelClient (required): /// client model Future testClientModelWithHttpInfo(ModelClient modelClient,) async { - // Verify required params are set. - if (modelClient == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: modelClient'); - } - // ignore: prefer_const_declarations final path = r'/fake'; // ignore: prefer_final_locals - Object postBody = modelClient; + Object? postBody = modelClient; final queryParams = []; final headerParams = {}; @@ -624,7 +583,7 @@ class FakeApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -637,7 +596,7 @@ class FakeApi { /// /// * [ModelClient] modelClient (required): /// client model - Future testClientModel(ModelClient modelClient,) async { + Future testClientModel(ModelClient modelClient,) async { final response = await testClientModelWithHttpInfo(modelClient,); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -645,11 +604,11 @@ class FakeApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'ModelClient',) as ModelClient; } - return Future.value(); + return null; } /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -701,26 +660,12 @@ class FakeApi { /// /// * [String] callback: /// None - Future testEndpointParametersWithHttpInfo(num number, double double_, String patternWithoutDelimiter, String byte, { int integer, int int32, int int64, double float, String string, MultipartFile binary, DateTime date, DateTime dateTime, String password, String callback, }) async { - // Verify required params are set. - if (number == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: number'); - } - if (double_ == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: double_'); - } - if (patternWithoutDelimiter == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: patternWithoutDelimiter'); - } - if (byte == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: byte'); - } - + Future testEndpointParametersWithHttpInfo(num number, double double_, String patternWithoutDelimiter, String byte, { int? integer, int? int32, int? int64, double? float, String? string, MultipartFile? binary, DateTime? date, DateTime? dateTime, String? password, String? callback, }) async { // ignore: prefer_const_declarations final path = r'/fake'; // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; @@ -776,7 +721,7 @@ class FakeApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -828,7 +773,7 @@ class FakeApi { /// /// * [String] callback: /// None - Future testEndpointParameters(num number, double double_, String patternWithoutDelimiter, String byte, { int integer, int int32, int int64, double float, String string, MultipartFile binary, DateTime date, DateTime dateTime, String password, String callback, }) async { + Future testEndpointParameters(num number, double double_, String patternWithoutDelimiter, String byte, { int? integer, int? int32, int? int64, double? float, String? string, MultipartFile? binary, DateTime? date, DateTime? dateTime, String? password, String? callback, }) async { final response = await testEndpointParametersWithHttpInfo(number, double_, patternWithoutDelimiter, byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback, ); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -866,30 +811,28 @@ class FakeApi { /// /// * [String] enumFormString: /// Form parameter enum test (string) - Future testEnumParametersWithHttpInfo({ List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, int enumQueryInteger, double enumQueryDouble, List enumFormStringArray, String enumFormString, }) async { - // Verify required params are set. - + Future testEnumParametersWithHttpInfo({ List? enumHeaderStringArray, String? enumHeaderString, List? enumQueryStringArray, String? enumQueryString, int? enumQueryInteger, double? enumQueryDouble, List? enumFormStringArray, String? enumFormString, }) async { // ignore: prefer_const_declarations final path = r'/fake'; // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; final formParams = {}; if (enumQueryStringArray != null) { - queryParams.addAll(_convertParametersForCollectionFormat('multi', 'enum_query_string_array', enumQueryStringArray)); + queryParams.addAll(_queryParams('multi', 'enum_query_string_array', enumQueryStringArray)); } if (enumQueryString != null) { - queryParams.addAll(_convertParametersForCollectionFormat('', 'enum_query_string', enumQueryString)); + queryParams.addAll(_queryParams('', 'enum_query_string', enumQueryString)); } if (enumQueryInteger != null) { - queryParams.addAll(_convertParametersForCollectionFormat('', 'enum_query_integer', enumQueryInteger)); + queryParams.addAll(_queryParams('', 'enum_query_integer', enumQueryInteger)); } if (enumQueryDouble != null) { - queryParams.addAll(_convertParametersForCollectionFormat('', 'enum_query_double', enumQueryDouble)); + queryParams.addAll(_queryParams('', 'enum_query_double', enumQueryDouble)); } if (enumHeaderStringArray != null) { @@ -916,7 +859,7 @@ class FakeApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -950,7 +893,7 @@ class FakeApi { /// /// * [String] enumFormString: /// Form parameter enum test (string) - Future testEnumParameters({ List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, int enumQueryInteger, double enumQueryDouble, List enumFormStringArray, String enumFormString, }) async { + Future testEnumParameters({ List? enumHeaderStringArray, String? enumHeaderString, List? enumQueryStringArray, String? enumQueryString, int? enumQueryInteger, double? enumQueryDouble, List? enumFormStringArray, String? enumFormString, }) async { final response = await testEnumParametersWithHttpInfo( enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, ); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -982,35 +925,24 @@ class FakeApi { /// /// * [int] int64Group: /// Integer in group parameters - Future testGroupParametersWithHttpInfo(int requiredStringGroup, bool requiredBooleanGroup, int requiredInt64Group, { int stringGroup, bool booleanGroup, int int64Group, }) async { - // Verify required params are set. - if (requiredStringGroup == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: requiredStringGroup'); - } - if (requiredBooleanGroup == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: requiredBooleanGroup'); - } - if (requiredInt64Group == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: requiredInt64Group'); - } - + Future testGroupParametersWithHttpInfo(int requiredStringGroup, bool requiredBooleanGroup, int requiredInt64Group, { int? stringGroup, bool? booleanGroup, int? int64Group, }) async { // ignore: prefer_const_declarations final path = r'/fake'; // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; final formParams = {}; - queryParams.addAll(_convertParametersForCollectionFormat('', 'required_string_group', requiredStringGroup)); - queryParams.addAll(_convertParametersForCollectionFormat('', 'required_int64_group', requiredInt64Group)); + queryParams.addAll(_queryParams('', 'required_string_group', requiredStringGroup)); + queryParams.addAll(_queryParams('', 'required_int64_group', requiredInt64Group)); if (stringGroup != null) { - queryParams.addAll(_convertParametersForCollectionFormat('', 'string_group', stringGroup)); + queryParams.addAll(_queryParams('', 'string_group', stringGroup)); } if (int64Group != null) { - queryParams.addAll(_convertParametersForCollectionFormat('', 'int64_group', int64Group)); + queryParams.addAll(_queryParams('', 'int64_group', int64Group)); } headerParams[r'required_boolean_group'] = parameterToString(requiredBooleanGroup); @@ -1029,7 +961,7 @@ class FakeApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -1057,7 +989,7 @@ class FakeApi { /// /// * [int] int64Group: /// Integer in group parameters - Future testGroupParameters(int requiredStringGroup, bool requiredBooleanGroup, int requiredInt64Group, { int stringGroup, bool booleanGroup, int int64Group, }) async { + Future testGroupParameters(int requiredStringGroup, bool requiredBooleanGroup, int requiredInt64Group, { int? stringGroup, bool? booleanGroup, int? int64Group, }) async { final response = await testGroupParametersWithHttpInfo(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group, ); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -1073,16 +1005,11 @@ class FakeApi { /// * [Map] requestBody (required): /// request body Future testInlineAdditionalPropertiesWithHttpInfo(Map requestBody,) async { - // Verify required params are set. - if (requestBody == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: requestBody'); - } - // ignore: prefer_const_declarations final path = r'/fake/inline-additionalProperties'; // ignore: prefer_final_locals - Object postBody = requestBody; + Object? postBody = requestBody; final queryParams = []; final headerParams = {}; @@ -1099,7 +1026,7 @@ class FakeApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -1129,19 +1056,11 @@ class FakeApi { /// * [String] param2 (required): /// field2 Future testJsonFormDataWithHttpInfo(String param, String param2,) async { - // Verify required params are set. - if (param == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: param'); - } - if (param2 == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: param2'); - } - // ignore: prefer_const_declarations final path = r'/fake/jsonFormData'; // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; @@ -1164,7 +1083,7 @@ class FakeApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -1204,46 +1123,26 @@ class FakeApi { /// * [String] allowEmpty (required): /// /// * [Map] language: - Future testQueryParameterCollectionFormatWithHttpInfo(List pipe, List ioutil, List http, List url, List context, String allowEmpty, { Map language, }) async { - // Verify required params are set. - if (pipe == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: pipe'); - } - if (ioutil == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: ioutil'); - } - if (http == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: http'); - } - if (url == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: url'); - } - if (context == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: context'); - } - if (allowEmpty == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: allowEmpty'); - } - + Future testQueryParameterCollectionFormatWithHttpInfo(List pipe, List ioutil, List http, List url, List context, String allowEmpty, { Map? language, }) async { // ignore: prefer_const_declarations final path = r'/fake/test-query-parameters'; // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; final formParams = {}; - queryParams.addAll(_convertParametersForCollectionFormat('pipes', 'pipe', pipe)); - queryParams.addAll(_convertParametersForCollectionFormat('csv', 'ioutil', ioutil)); - queryParams.addAll(_convertParametersForCollectionFormat('ssv', 'http', http)); - queryParams.addAll(_convertParametersForCollectionFormat('csv', 'url', url)); - queryParams.addAll(_convertParametersForCollectionFormat('multi', 'context', context)); + queryParams.addAll(_queryParams('pipes', 'pipe', pipe)); + queryParams.addAll(_queryParams('csv', 'ioutil', ioutil)); + queryParams.addAll(_queryParams('ssv', 'http', http)); + queryParams.addAll(_queryParams('csv', 'url', url)); + queryParams.addAll(_queryParams('multi', 'context', context)); if (language != null) { - queryParams.addAll(_convertParametersForCollectionFormat('', 'language', language)); + queryParams.addAll(_queryParams('', 'language', language)); } - queryParams.addAll(_convertParametersForCollectionFormat('', 'allowEmpty', allowEmpty)); + queryParams.addAll(_queryParams('', 'allowEmpty', allowEmpty)); const authNames = []; const contentTypes = []; @@ -1256,7 +1155,7 @@ class FakeApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -1278,7 +1177,7 @@ class FakeApi { /// * [String] allowEmpty (required): /// /// * [Map] language: - Future testQueryParameterCollectionFormat(List pipe, List ioutil, List http, List url, List context, String allowEmpty, { Map language, }) async { + Future testQueryParameterCollectionFormat(List pipe, List ioutil, List http, List url, List context, String allowEmpty, { Map? language, }) async { final response = await testQueryParameterCollectionFormatWithHttpInfo(pipe, ioutil, http, url, context, allowEmpty, language: language, ); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart index 8686e9e7bab5..158c127195bf 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -12,7 +12,7 @@ part of openapi.api; class FakeClassnameTags123Api { - FakeClassnameTags123Api([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; + FakeClassnameTags123Api([ApiClient? apiClient]) : apiClient = apiClient ?? defaultApiClient; final ApiClient apiClient; @@ -27,16 +27,11 @@ class FakeClassnameTags123Api { /// * [ModelClient] modelClient (required): /// client model Future testClassnameWithHttpInfo(ModelClient modelClient,) async { - // Verify required params are set. - if (modelClient == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: modelClient'); - } - // ignore: prefer_const_declarations final path = r'/fake_classname_test'; // ignore: prefer_final_locals - Object postBody = modelClient; + Object? postBody = modelClient; final queryParams = []; final headerParams = {}; @@ -53,7 +48,7 @@ class FakeClassnameTags123Api { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -66,7 +61,7 @@ class FakeClassnameTags123Api { /// /// * [ModelClient] modelClient (required): /// client model - Future testClassname(ModelClient modelClient,) async { + Future testClassname(ModelClient modelClient,) async { final response = await testClassnameWithHttpInfo(modelClient,); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -74,10 +69,10 @@ class FakeClassnameTags123Api { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'ModelClient',) as ModelClient; } - return Future.value(); + return null; } } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/pet_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/pet_api.dart index 8cfcf9eb9a09..a91754608983 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/pet_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/pet_api.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -12,7 +12,7 @@ part of openapi.api; class PetApi { - PetApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; + PetApi([ApiClient? apiClient]) : apiClient = apiClient ?? defaultApiClient; final ApiClient apiClient; @@ -25,16 +25,11 @@ class PetApi { /// * [Pet] pet (required): /// Pet object that needs to be added to the store Future addPetWithHttpInfo(Pet pet,) async { - // Verify required params are set. - if (pet == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: pet'); - } - // ignore: prefer_const_declarations final path = r'/pet'; // ignore: prefer_final_locals - Object postBody = pet; + Object? postBody = pet; final queryParams = []; final headerParams = {}; @@ -51,7 +46,7 @@ class PetApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -79,18 +74,13 @@ class PetApi { /// Pet id to delete /// /// * [String] apiKey: - Future deletePetWithHttpInfo(int petId, { String apiKey, }) async { - // Verify required params are set. - if (petId == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: petId'); - } - + Future deletePetWithHttpInfo(int petId, { String? apiKey, }) async { // ignore: prefer_const_declarations final path = r'/pet/{petId}' .replaceAll('{petId}', petId.toString()); // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; @@ -111,7 +101,7 @@ class PetApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -124,7 +114,7 @@ class PetApi { /// Pet id to delete /// /// * [String] apiKey: - Future deletePet(int petId, { String apiKey, }) async { + Future deletePet(int petId, { String? apiKey, }) async { final response = await deletePetWithHttpInfo(petId, apiKey: apiKey, ); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -142,22 +132,17 @@ class PetApi { /// * [List] status (required): /// Status values that need to be considered for filter Future findPetsByStatusWithHttpInfo(List status,) async { - // Verify required params are set. - if (status == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: status'); - } - // ignore: prefer_const_declarations final path = r'/pet/findByStatus'; // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; final formParams = {}; - queryParams.addAll(_convertParametersForCollectionFormat('csv', 'status', status)); + queryParams.addAll(_queryParams('csv', 'status', status)); const authNames = ['petstore_auth']; const contentTypes = []; @@ -170,7 +155,7 @@ class PetApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -183,7 +168,7 @@ class PetApi { /// /// * [List] status (required): /// Status values that need to be considered for filter - Future> findPetsByStatus(List status,) async { + Future?> findPetsByStatus(List status,) async { final response = await findPetsByStatusWithHttpInfo(status,); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -191,14 +176,14 @@ class PetApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { final responseBody = await _decodeBodyBytes(response); return (await apiClient.deserializeAsync(responseBody, 'List') as List) .cast() - .toList(growable: false); + .toList(); } - return Future>.value(); + return null; } /// Finds Pets by tags @@ -212,22 +197,17 @@ class PetApi { /// * [Set] tags (required): /// Tags to filter by Future findPetsByTagsWithHttpInfo(Set tags,) async { - // Verify required params are set. - if (tags == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: tags'); - } - // ignore: prefer_const_declarations final path = r'/pet/findByTags'; // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; final formParams = {}; - queryParams.addAll(_convertParametersForCollectionFormat('csv', 'tags', tags)); + queryParams.addAll(_queryParams('csv', 'tags', tags)); const authNames = ['petstore_auth']; const contentTypes = []; @@ -240,7 +220,7 @@ class PetApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -253,7 +233,7 @@ class PetApi { /// /// * [Set] tags (required): /// Tags to filter by - Future> findPetsByTags(Set tags,) async { + Future?> findPetsByTags(Set tags,) async { final response = await findPetsByTagsWithHttpInfo(tags,); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -261,14 +241,14 @@ class PetApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { final responseBody = await _decodeBodyBytes(response); return (await apiClient.deserializeAsync(responseBody, 'Set') as List) .cast() .toSet(); } - return Future>.value(); + return null; } /// Find pet by ID @@ -282,17 +262,12 @@ class PetApi { /// * [int] petId (required): /// ID of pet to return Future getPetByIdWithHttpInfo(int petId,) async { - // Verify required params are set. - if (petId == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: petId'); - } - // ignore: prefer_const_declarations final path = r'/pet/{petId}' .replaceAll('{petId}', petId.toString()); // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; @@ -309,7 +284,7 @@ class PetApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -322,7 +297,7 @@ class PetApi { /// /// * [int] petId (required): /// ID of pet to return - Future getPetById(int petId,) async { + Future getPetById(int petId,) async { final response = await getPetByIdWithHttpInfo(petId,); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -330,11 +305,11 @@ class PetApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'Pet',) as Pet; } - return Future.value(); + return null; } /// Update an existing pet @@ -346,16 +321,11 @@ class PetApi { /// * [Pet] pet (required): /// Pet object that needs to be added to the store Future updatePetWithHttpInfo(Pet pet,) async { - // Verify required params are set. - if (pet == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: pet'); - } - // ignore: prefer_const_declarations final path = r'/pet'; // ignore: prefer_final_locals - Object postBody = pet; + Object? postBody = pet; final queryParams = []; final headerParams = {}; @@ -372,7 +342,7 @@ class PetApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -404,18 +374,13 @@ class PetApi { /// /// * [String] status: /// Updated status of the pet - Future updatePetWithFormWithHttpInfo(int petId, { String name, String status, }) async { - // Verify required params are set. - if (petId == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: petId'); - } - + Future updatePetWithFormWithHttpInfo(int petId, { String? name, String? status, }) async { // ignore: prefer_const_declarations final path = r'/pet/{petId}' .replaceAll('{petId}', petId.toString()); // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; @@ -438,7 +403,7 @@ class PetApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -455,7 +420,7 @@ class PetApi { /// /// * [String] status: /// Updated status of the pet - Future updatePetWithForm(int petId, { String name, String status, }) async { + Future updatePetWithForm(int petId, { String? name, String? status, }) async { final response = await updatePetWithFormWithHttpInfo(petId, name: name, status: status, ); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -476,18 +441,13 @@ class PetApi { /// /// * [MultipartFile] file: /// file to upload - Future uploadFileWithHttpInfo(int petId, { String additionalMetadata, MultipartFile file, }) async { - // Verify required params are set. - if (petId == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: petId'); - } - + Future uploadFileWithHttpInfo(int petId, { String? additionalMetadata, MultipartFile? file, }) async { // ignore: prefer_const_declarations final path = r'/pet/{petId}/uploadImage' .replaceAll('{petId}', petId.toString()); // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; @@ -518,7 +478,7 @@ class PetApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -535,7 +495,7 @@ class PetApi { /// /// * [MultipartFile] file: /// file to upload - Future uploadFile(int petId, { String additionalMetadata, MultipartFile file, }) async { + Future uploadFile(int petId, { String? additionalMetadata, MultipartFile? file, }) async { final response = await uploadFileWithHttpInfo(petId, additionalMetadata: additionalMetadata, file: file, ); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -543,11 +503,11 @@ class PetApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'ApiResponse',) as ApiResponse; } - return Future.value(); + return null; } /// uploads an image (required) @@ -564,21 +524,13 @@ class PetApi { /// /// * [String] additionalMetadata: /// Additional data to pass to server - Future uploadFileWithRequiredFileWithHttpInfo(int petId, MultipartFile requiredFile, { String additionalMetadata, }) async { - // Verify required params are set. - if (petId == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: petId'); - } - if (requiredFile == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: requiredFile'); - } - + Future uploadFileWithRequiredFileWithHttpInfo(int petId, MultipartFile requiredFile, { String? additionalMetadata, }) async { // ignore: prefer_const_declarations final path = r'/fake/{petId}/uploadImageWithRequiredFile' .replaceAll('{petId}', petId.toString()); // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; @@ -609,7 +561,7 @@ class PetApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -626,7 +578,7 @@ class PetApi { /// /// * [String] additionalMetadata: /// Additional data to pass to server - Future uploadFileWithRequiredFile(int petId, MultipartFile requiredFile, { String additionalMetadata, }) async { + Future uploadFileWithRequiredFile(int petId, MultipartFile requiredFile, { String? additionalMetadata, }) async { final response = await uploadFileWithRequiredFileWithHttpInfo(petId, requiredFile, additionalMetadata: additionalMetadata, ); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -634,10 +586,10 @@ class PetApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'ApiResponse',) as ApiResponse; } - return Future.value(); + return null; } } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/store_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/store_api.dart index 121f16a9f90d..3cb580f1e197 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/store_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/store_api.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -12,7 +12,7 @@ part of openapi.api; class StoreApi { - StoreApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; + StoreApi([ApiClient? apiClient]) : apiClient = apiClient ?? defaultApiClient; final ApiClient apiClient; @@ -27,17 +27,12 @@ class StoreApi { /// * [String] orderId (required): /// ID of the order that needs to be deleted Future deleteOrderWithHttpInfo(String orderId,) async { - // Verify required params are set. - if (orderId == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: orderId'); - } - // ignore: prefer_const_declarations final path = r'/store/order/{order_id}' .replaceAll('{order_id}', orderId); // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; @@ -54,7 +49,7 @@ class StoreApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -84,7 +79,7 @@ class StoreApi { final path = r'/store/inventory'; // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; @@ -101,7 +96,7 @@ class StoreApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -109,7 +104,7 @@ class StoreApi { /// Returns pet inventories by status /// /// Returns a map of status codes to quantities - Future> getInventory() async { + Future?> getInventory() async { final response = await getInventoryWithHttpInfo(); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -117,11 +112,11 @@ class StoreApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return Map.from(await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'Map'),); } - return Future>.value(); + return null; } /// Find purchase order by ID @@ -135,17 +130,12 @@ class StoreApi { /// * [int] orderId (required): /// ID of pet that needs to be fetched Future getOrderByIdWithHttpInfo(int orderId,) async { - // Verify required params are set. - if (orderId == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: orderId'); - } - // ignore: prefer_const_declarations final path = r'/store/order/{order_id}' .replaceAll('{order_id}', orderId.toString()); // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; @@ -162,7 +152,7 @@ class StoreApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -175,7 +165,7 @@ class StoreApi { /// /// * [int] orderId (required): /// ID of pet that needs to be fetched - Future getOrderById(int orderId,) async { + Future getOrderById(int orderId,) async { final response = await getOrderByIdWithHttpInfo(orderId,); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -183,11 +173,11 @@ class StoreApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'Order',) as Order; } - return Future.value(); + return null; } /// Place an order for a pet @@ -199,16 +189,11 @@ class StoreApi { /// * [Order] order (required): /// order placed for purchasing the pet Future placeOrderWithHttpInfo(Order order,) async { - // Verify required params are set. - if (order == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: order'); - } - // ignore: prefer_const_declarations final path = r'/store/order'; // ignore: prefer_final_locals - Object postBody = order; + Object? postBody = order; final queryParams = []; final headerParams = {}; @@ -225,7 +210,7 @@ class StoreApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -236,7 +221,7 @@ class StoreApi { /// /// * [Order] order (required): /// order placed for purchasing the pet - Future placeOrder(Order order,) async { + Future placeOrder(Order order,) async { final response = await placeOrderWithHttpInfo(order,); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -244,10 +229,10 @@ class StoreApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'Order',) as Order; } - return Future.value(); + return null; } } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/user_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/user_api.dart index 9838b689d7a7..7cc0b7e18224 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/user_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/user_api.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -12,7 +12,7 @@ part of openapi.api; class UserApi { - UserApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; + UserApi([ApiClient? apiClient]) : apiClient = apiClient ?? defaultApiClient; final ApiClient apiClient; @@ -27,16 +27,11 @@ class UserApi { /// * [User] user (required): /// Created user object Future createUserWithHttpInfo(User user,) async { - // Verify required params are set. - if (user == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: user'); - } - // ignore: prefer_const_declarations final path = r'/user'; // ignore: prefer_final_locals - Object postBody = user; + Object? postBody = user; final queryParams = []; final headerParams = {}; @@ -53,7 +48,7 @@ class UserApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -82,16 +77,11 @@ class UserApi { /// * [List] user (required): /// List of user object Future createUsersWithArrayInputWithHttpInfo(List user,) async { - // Verify required params are set. - if (user == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: user'); - } - // ignore: prefer_const_declarations final path = r'/user/createWithArray'; // ignore: prefer_final_locals - Object postBody = user; + Object? postBody = user; final queryParams = []; final headerParams = {}; @@ -108,7 +98,7 @@ class UserApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -135,16 +125,11 @@ class UserApi { /// * [List] user (required): /// List of user object Future createUsersWithListInputWithHttpInfo(List user,) async { - // Verify required params are set. - if (user == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: user'); - } - // ignore: prefer_const_declarations final path = r'/user/createWithList'; // ignore: prefer_final_locals - Object postBody = user; + Object? postBody = user; final queryParams = []; final headerParams = {}; @@ -161,7 +146,7 @@ class UserApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -190,17 +175,12 @@ class UserApi { /// * [String] username (required): /// The name that needs to be deleted Future deleteUserWithHttpInfo(String username,) async { - // Verify required params are set. - if (username == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: username'); - } - // ignore: prefer_const_declarations final path = r'/user/{username}' .replaceAll('{username}', username); // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; @@ -217,7 +197,7 @@ class UserApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -246,17 +226,12 @@ class UserApi { /// * [String] username (required): /// The name that needs to be fetched. Use user1 for testing. Future getUserByNameWithHttpInfo(String username,) async { - // Verify required params are set. - if (username == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: username'); - } - // ignore: prefer_const_declarations final path = r'/user/{username}' .replaceAll('{username}', username); // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; @@ -273,7 +248,7 @@ class UserApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -284,7 +259,7 @@ class UserApi { /// /// * [String] username (required): /// The name that needs to be fetched. Use user1 for testing. - Future getUserByName(String username,) async { + Future getUserByName(String username,) async { final response = await getUserByNameWithHttpInfo(username,); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -292,11 +267,11 @@ class UserApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'User',) as User; } - return Future.value(); + return null; } /// Logs user into the system @@ -311,26 +286,18 @@ class UserApi { /// * [String] password (required): /// The password for login in clear text Future loginUserWithHttpInfo(String username, String password,) async { - // Verify required params are set. - if (username == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: username'); - } - if (password == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: password'); - } - // ignore: prefer_const_declarations final path = r'/user/login'; // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; final formParams = {}; - queryParams.addAll(_convertParametersForCollectionFormat('', 'username', username)); - queryParams.addAll(_convertParametersForCollectionFormat('', 'password', password)); + queryParams.addAll(_queryParams('', 'username', username)); + queryParams.addAll(_queryParams('', 'password', password)); const authNames = []; const contentTypes = []; @@ -343,7 +310,7 @@ class UserApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -357,7 +324,7 @@ class UserApi { /// /// * [String] password (required): /// The password for login in clear text - Future loginUser(String username, String password,) async { + Future loginUser(String username, String password,) async { final response = await loginUserWithHttpInfo(username, password,); if (response.statusCode >= HttpStatus.badRequest) { throw ApiException(response.statusCode, await _decodeBodyBytes(response)); @@ -365,11 +332,11 @@ class UserApi { // When a remote server returns no body with a status of 204, we shall not decode it. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" // FormatException when trying to decode an empty string. - if (response.body != null && response.statusCode != HttpStatus.noContent) { + if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) { return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'String',) as String; } - return Future.value(); + return null; } /// Logs out current logged in user session @@ -380,7 +347,7 @@ class UserApi { final path = r'/user/logout'; // ignore: prefer_final_locals - Object postBody; + Object? postBody; final queryParams = []; final headerParams = {}; @@ -397,7 +364,7 @@ class UserApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } @@ -424,20 +391,12 @@ class UserApi { /// * [User] user (required): /// Updated user object Future updateUserWithHttpInfo(String username, User user,) async { - // Verify required params are set. - if (username == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: username'); - } - if (user == null) { - throw ApiException(HttpStatus.badRequest, 'Missing required param: user'); - } - // ignore: prefer_const_declarations final path = r'/user/{username}' .replaceAll('{username}', username); // ignore: prefer_final_locals - Object postBody = user; + Object? postBody = user; final queryParams = []; final headerParams = {}; @@ -454,7 +413,7 @@ class UserApi { postBody, headerParams, formParams, - contentTypes.isEmpty ? null : contentTypes[0], + contentTypes.isEmpty ? null : contentTypes.first, authNames, ); } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_client.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_client.dart index d3c64b9adc3c..8277ac92e7ca 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_client.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_client.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -30,12 +30,7 @@ class ApiClient { Client get client => _client; /// Requests to use a new HTTP [Client] in this class. - /// - /// If the [newClient] is null, an [ArgumentError] is thrown. set client(Client newClient) { - if (newClient == null) { - throw ArgumentError('New client instance cannot be null.'); - } _client = newClient; } @@ -52,7 +47,7 @@ class ApiClient { /// or deleted. Map get authentications => Map.unmodifiable(_authentications); - T getAuthentication(String name) { + T? getAuthentication(String name) { final authentication = _authentications[name]; return authentication is T ? authentication : null; } @@ -63,35 +58,28 @@ class ApiClient { String path, String method, List queryParams, - Object body, + Object? body, Map headerParams, Map formParams, - String nullableContentType, + String? contentType, List authNames, ) async { _updateParamsForAuth(authNames, queryParams, headerParams); headerParams.addAll(_defaultHeaderMap); + if (contentType != null) { + headerParams['Content-Type'] = contentType; + } - final urlEncodedQueryParams = queryParams - .where((param) => param.value != null) - .map((param) => '$param'); - - final queryString = urlEncodedQueryParams.isNotEmpty - ? '?${urlEncodedQueryParams.join('&')}' - : ''; - + final urlEncodedQueryParams = queryParams.map((param) => '$param'); + final queryString = urlEncodedQueryParams.isNotEmpty ? '?${urlEncodedQueryParams.join('&')}' : ''; final uri = Uri.parse('$basePath$path$queryString'); - if (nullableContentType != null) { - headerParams['Content-Type'] = nullableContentType; - } - try { // Special case for uploading a single file which isn't a 'multipart/form-data'. if ( - body is MultipartFile && (nullableContentType == null || - !nullableContentType.toLowerCase().startsWith('multipart/form-data')) + body is MultipartFile && (contentType == null || + !contentType.toLowerCase().startsWith('multipart/form-data')) ) { final request = StreamedRequest(method, uri); request.headers.addAll(headerParams); @@ -117,7 +105,7 @@ class ApiClient { return Response.fromStream(response); } - final msgBody = nullableContentType == 'application/x-www-form-urlencoded' + final msgBody = contentType == 'application/x-www-form-urlencoded' ? formParams : await serializeAsync(body); final nullableHeaderParams = headerParams.isEmpty ? null : headerParams; @@ -130,41 +118,69 @@ class ApiClient { case 'HEAD': return await _client.head(uri, headers: nullableHeaderParams,); case 'GET': return await _client.get(uri, headers: nullableHeaderParams,); } - } on SocketException catch (e, trace) { - throw ApiException.withInner(HttpStatus.badRequest, 'Socket operation failed: $method $path', e, trace,); - } on TlsException catch (e, trace) { - throw ApiException.withInner(HttpStatus.badRequest, 'TLS/SSL communication failed: $method $path', e, trace,); - } on IOException catch (e, trace) { - throw ApiException.withInner(HttpStatus.badRequest, 'I/O operation failed: $method $path', e, trace,); - } on ClientException catch (e, trace) { - throw ApiException.withInner(HttpStatus.badRequest, 'HTTP connection failed: $method $path', e, trace,); - } on Exception catch (e, trace) { - throw ApiException.withInner(HttpStatus.badRequest, 'Exception occurred: $method $path', e, trace,); + } on SocketException catch (error, trace) { + throw ApiException.withInner( + HttpStatus.badRequest, + 'Socket operation failed: $method $path', + error, + trace, + ); + } on TlsException catch (error, trace) { + throw ApiException.withInner( + HttpStatus.badRequest, + 'TLS/SSL communication failed: $method $path', + error, + trace, + ); + } on IOException catch (error, trace) { + throw ApiException.withInner( + HttpStatus.badRequest, + 'I/O operation failed: $method $path', + error, + trace, + ); + } on ClientException catch (error, trace) { + throw ApiException.withInner( + HttpStatus.badRequest, + 'HTTP connection failed: $method $path', + error, + trace, + ); + } on Exception catch (error, trace) { + throw ApiException.withInner( + HttpStatus.badRequest, + 'Exception occurred: $method $path', + error, + trace, + ); } - throw ApiException(HttpStatus.badRequest, 'Invalid HTTP operation: $method $path',); + throw ApiException( + HttpStatus.badRequest, + 'Invalid HTTP operation: $method $path', + ); } - Future deserializeAsync(String json, String targetType, {bool growable}) async => + Future deserializeAsync(String json, String targetType, {bool growable = false,}) async => // ignore: deprecated_member_use_from_same_package deserialize(json, targetType, growable: growable); @Deprecated('Scheduled for removal in OpenAPI Generator 6.x. Use deserializeAsync() instead.') - dynamic deserialize(String json, String targetType, {bool growable}) { + dynamic deserialize(String json, String targetType, {bool growable = false,}) { // Remove all spaces. Necessary for regular expressions as well. targetType = targetType.replaceAll(' ', ''); // ignore: parameter_assignments // If the expected target type is String, nothing to do... return targetType == 'String' ? json - : _deserialize(jsonDecode(json), targetType, growable: growable == true); + : _deserialize(jsonDecode(json), targetType, growable: growable); } // ignore: deprecated_member_use_from_same_package - Future serializeAsync(Object value) async => serialize(value); + Future serializeAsync(Object? value) async => serialize(value); @Deprecated('Scheduled for removal in OpenAPI Generator 6.x. Use serializeAsync() instead.') - String serialize(Object value) => value == null ? '' : json.encode(value); + String serialize(Object? value) => value == null ? '' : json.encode(value); /// Update query and header parameters based on authentication settings. /// @param authNames The authentications to apply @@ -182,7 +198,7 @@ class ApiClient { } } - static dynamic _deserialize(dynamic value, String targetType, {bool growable}) { + static dynamic _deserialize(dynamic value, String targetType, {bool growable = false}) { try { switch (targetType) { case 'String': @@ -290,24 +306,21 @@ class ApiClient { case 'User': return User.fromJson(value); default: - Match match; - if (value is List && (match = _regList.firstMatch(targetType)) != null) { - targetType = match[1]; // ignore: parameter_assignments + dynamic match; + if (value is List && (match = _regList.firstMatch(targetType)?.group(1)) != null) { return value - .map((dynamic v) => _deserialize(v, targetType, growable: growable)) + .map((dynamic v) => _deserialize(v, match, growable: growable,)) .toList(growable: growable); } - if (value is Set && (match = _regSet.firstMatch(targetType)) != null) { - targetType = match[1]; // ignore: parameter_assignments + if (value is Set && (match = _regSet.firstMatch(targetType)?.group(1)) != null) { return value - .map((dynamic v) => _deserialize(v, targetType, growable: growable)) + .map((dynamic v) => _deserialize(v, match, growable: growable,)) .toSet(); } - if (value is Map && (match = _regMap.firstMatch(targetType)) != null) { - targetType = match[1]; // ignore: parameter_assignments + if (value is Map && (match = _regMap.firstMatch(targetType)?.group(1)) != null) { return Map.fromIterables( value.keys.cast(), - value.values.map((dynamic v) => _deserialize(v, targetType, growable: growable)), + value.values.map((dynamic v) => _deserialize(v, match, growable: growable,)), ); } } @@ -321,9 +334,9 @@ class ApiClient { /// Primarily intended for use in an isolate. class DeserializationMessage { const DeserializationMessage({ - @required this.json, - @required this.targetType, - this.growable, + required this.json, + required this.targetType, + this.growable = false, }); /// The JSON value to deserialize. @@ -347,9 +360,9 @@ Future deserializeAsync(DeserializationMessage message) async { : ApiClient._deserialize( jsonDecode(message.json), targetType, - growable: message.growable == true, + growable: message.growable, ); } /// Primarily intended for use in an isolate. -Future serializeAsync(Object value) async => value == null ? '' : json.encode(value); +Future serializeAsync(Object? value) async => value == null ? '' : json.encode(value); diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_exception.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_exception.dart index 8ffc340b4c9d..796f7f7ee74e 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_exception.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_exception.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -16,9 +16,9 @@ class ApiException implements Exception { ApiException.withInner(this.code, this.message, this.innerException, this.stackTrace); int code = 0; - String message; - Exception innerException; - StackTrace stackTrace; + String? message; + Exception? innerException; + StackTrace? stackTrace; @override String toString() { diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_helper.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_helper.dart index bdb7b1fc166a..1aaf1dae8eb3 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_helper.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_helper.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -21,32 +21,27 @@ class QueryParam { } // Ported from the Java version. -Iterable _convertParametersForCollectionFormat( - String collectionFormat, - String name, - dynamic value, -) { +Iterable _queryParams(String collectionFormat, String name, dynamic value,) { + // Assertions to run in debug mode only. + assert(name.isNotEmpty, 'Parameter cannot be an empty string.'); + final params = []; - // preconditions - if (name != null && name.isNotEmpty && value != null) { - if (value is List) { - if (collectionFormat == 'multi') { - return value.map((dynamic v) => QueryParam(name, parameterToString(v)),); - } + if (value is List) { + if (collectionFormat == 'multi') { + return value.map((dynamic v) => QueryParam(name, parameterToString(v)),); + } - // Default collection format is 'csv'. - if (collectionFormat == null || collectionFormat.isEmpty) { - // ignore: parameter_assignments - collectionFormat = 'csv'; - } + // Default collection format is 'csv'. + if (collectionFormat.isEmpty) { + collectionFormat = 'csv'; // ignore: parameter_assignments + } - final delimiter = _delimiters[collectionFormat] ?? ','; + final delimiter = _delimiters[collectionFormat] ?? ','; - params.add(QueryParam(name, value.map(parameterToString).join(delimiter)),); - } else { - params.add(QueryParam(name, parameterToString(value),)); - } + params.add(QueryParam(name, value.map(parameterToString).join(delimiter),)); + } else if (value != null) { + params.add(QueryParam(name, parameterToString(value))); } return params; @@ -83,27 +78,27 @@ String parameterToString(dynamic value) { Future _decodeBodyBytes(Response response) async { final contentType = response.headers['content-type']; return contentType != null && contentType.toLowerCase().startsWith('application/json') - ? response.bodyBytes == null ? null : utf8.decode(response.bodyBytes) + ? response.bodyBytes.isEmpty ? '' : utf8.decode(response.bodyBytes) : response.body; } /// Returns a valid [T] value found at the specified Map [key], null otherwise. -T mapValueOfType(dynamic map, String key) { +T? mapValueOfType(dynamic map, String key) { final dynamic value = map is Map ? map[key] : null; return value is T ? value : null; } /// Returns a valid Map found at the specified Map [key], null otherwise. -Map mapCastOfType(dynamic map, String key) { +Map? mapCastOfType(dynamic map, String key) { final dynamic value = map is Map ? map[key] : null; return value is Map ? value.cast() : null; } /// Returns a valid [DateTime] found at the specified Map [key], null otherwise. -DateTime mapDateTime(dynamic map, String key, [String pattern]) { +DateTime? mapDateTime(dynamic map, String key, [String? pattern]) { final dynamic value = map is Map ? map[key] : null; if (value != null) { - int millis; + int? millis; if (value is int) { millis = value; } else if (value is String) { diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/api_key_auth.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/api_key_auth.dart index 0c2303af09e9..e304eda321ee 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/api_key_auth.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/api_key_auth.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -16,23 +16,25 @@ class ApiKeyAuth implements Authentication { final String location; final String paramName; - String apiKeyPrefix; - String apiKey; + String apiKeyPrefix = ''; + String apiKey = ''; @override void applyToParams(List queryParams, Map headerParams) { - final value = apiKeyPrefix == null ? apiKey : '$apiKeyPrefix $apiKey'; + final paramValue = apiKeyPrefix.isEmpty ? apiKey : '$apiKeyPrefix $apiKey'; - if (location == 'query' && value != null) { - queryParams.add(QueryParam(paramName, value)); - } else if (location == 'header' && value != null) { - headerParams[paramName] = value; - } else if (location == 'cookie' && value != null) { - headerParams.update( - 'Cookie', - (existingCookie) => '$existingCookie; $paramName=$value', - ifAbsent: () => '$paramName=$value', - ); + if (paramValue.isNotEmpty) { + if (location == 'query') { + queryParams.add(QueryParam(paramName, paramValue)); + } else if (location == 'header') { + headerParams[paramName] = paramValue; + } else if (location == 'cookie') { + headerParams.update( + 'Cookie', + (existingCookie) => '$existingCookie; $paramName=$paramValue', + ifAbsent: () => '$paramName=$paramValue', + ); + } } } } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/authentication.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/authentication.dart index 4257e1900069..49baf7c46a9c 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/authentication.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/authentication.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/http_basic_auth.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/http_basic_auth.dart index 0494f402d958..81abd7185f2d 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/http_basic_auth.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/http_basic_auth.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -11,12 +11,16 @@ part of openapi.api; class HttpBasicAuth implements Authentication { + HttpBasicAuth({this.username = '', this.password = ''}); + String username; String password; @override void applyToParams(List queryParams, Map headerParams) { - final credentials = '${username ?? ''}:${password ?? ''}'; - headerParams['Authorization'] = 'Basic ${base64.encode(utf8.encode(credentials))}'; + if (username.isNotEmpty && password.isNotEmpty) { + final credentials = '$username:$password'; + headerParams['Authorization'] = 'Basic ${base64.encode(utf8.encode(credentials))}'; + } } } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/http_bearer_auth.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/http_bearer_auth.dart index 23e243523dd8..213f3483b8fb 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/http_bearer_auth.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/http_bearer_auth.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -21,19 +21,29 @@ class HttpBearerAuth implements Authentication { set accessToken(dynamic accessToken) { if (accessToken is! String && accessToken is! HttpBearerAuthProvider) { - throw ArgumentError('Type of Bearer accessToken should be a String or a String Function().'); + throw ArgumentError('accessToken value must be either a String or a String Function().'); } _accessToken = accessToken; } @override void applyToParams(List queryParams, Map headerParams) { + if (_accessToken == null) { + return; + } + + String accessToken; + if (_accessToken is String) { - headerParams['Authorization'] = 'Bearer $_accessToken'; + accessToken = _accessToken; } else if (_accessToken is HttpBearerAuthProvider) { - headerParams['Authorization'] = 'Bearer ${_accessToken()}'; + accessToken = _accessToken!(); } else { - throw ArgumentError('Type of Bearer accessToken should be a String or a String Function().'); + return; + } + + if (accessToken.isNotEmpty) { + headerParams['Authorization'] = 'Bearer $accessToken'; } } } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/oauth.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/oauth.dart index 9299ac13f5bf..e9b87cffb052 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/oauth.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/oauth.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -11,13 +11,13 @@ part of openapi.api; class OAuth implements Authentication { - OAuth({this.accessToken}); + OAuth({this.accessToken = ''}); String accessToken; @override void applyToParams(List queryParams, Map headerParams) { - if (accessToken != null) { + if (accessToken.isNotEmpty) { headerParams['Authorization'] = 'Bearer $accessToken'; } } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/additional_properties_class.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/additional_properties_class.dart index dc1f488f0b22..e82b8265bf59 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/additional_properties_class.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/additional_properties_class.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -28,68 +28,90 @@ class AdditionalPropertiesClass { @override int get hashCode => - // ignore: unnecessary_parenthesis - (mapProperty == null ? 0 : mapProperty.hashCode) + - (mapOfMapProperty == null ? 0 : mapOfMapProperty.hashCode); + // ignore: unnecessary_parenthesis + (mapProperty.hashCode) + + (mapOfMapProperty.hashCode); @override String toString() => 'AdditionalPropertiesClass[mapProperty=$mapProperty, mapOfMapProperty=$mapOfMapProperty]'; Map toJson() { final json = {}; - if (mapProperty != null) { json[r'map_property'] = mapProperty; - } - if (mapOfMapProperty != null) { json[r'map_of_map_property'] = mapOfMapProperty; - } return json; } /// Returns a new [AdditionalPropertiesClass] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static AdditionalPropertiesClass fromJson(dynamic value) { + static AdditionalPropertiesClass? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "AdditionalPropertiesClass[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "AdditionalPropertiesClass[$key]" has a null value in JSON.'); + }); + return true; + }()); + return AdditionalPropertiesClass( - mapProperty: mapCastOfType(json, r'map_property'), - mapOfMapProperty: mapCastOfType(json, r'map_of_map_property'), + mapProperty: mapCastOfType(json, r'map_property') ?? const {}, + mapOfMapProperty: mapCastOfType(json, r'map_of_map_property') ?? const {}, ); } return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(AdditionalPropertiesClass.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = AdditionalPropertiesClass.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = AdditionalPropertiesClass.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = AdditionalPropertiesClass.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of AdditionalPropertiesClass-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = AdditionalPropertiesClass.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = AdditionalPropertiesClass.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/animal.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/animal.dart index d138a87c008b..2d279e07c494 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/animal.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/animal.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -13,7 +13,7 @@ part of openapi.api; class Animal { /// Returns a new [Animal] instance. Animal({ - @required this.className, + required this.className, this.color = 'red', }); @@ -28,9 +28,9 @@ class Animal { @override int get hashCode => - // ignore: unnecessary_parenthesis - (className == null ? 0 : className.hashCode) + - (color == null ? 0 : color.hashCode); + // ignore: unnecessary_parenthesis + (className.hashCode) + + (color.hashCode); @override String toString() => 'Animal[className=$className, color=$color]'; @@ -38,56 +38,81 @@ class Animal { Map toJson() { final json = {}; json[r'className'] = className; - if (color != null) { json[r'color'] = color; - } return json; } /// Returns a new [Animal] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static Animal fromJson(dynamic value) { + static Animal? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "Animal[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "Animal[$key]" has a null value in JSON.'); + }); + return true; + }()); + return Animal( - className: mapValueOfType(json, r'className'), - color: mapValueOfType(json, r'color'), + className: mapValueOfType(json, r'className')!, + color: mapValueOfType(json, r'color') ?? 'red', ); } return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(Animal.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = Animal.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = Animal.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Animal.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of Animal-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = Animal.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Animal.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + 'className', + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/api_response.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/api_response.dart index bfd43366211f..6042baea5514 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/api_response.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/api_response.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -18,11 +18,29 @@ class ApiResponse { this.message, }); - int code; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? code; - String type; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? type; - String message; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? message; @override bool operator ==(Object other) => identical(this, other) || other is ApiResponse && @@ -32,10 +50,10 @@ class ApiResponse { @override int get hashCode => - // ignore: unnecessary_parenthesis - (code == null ? 0 : code.hashCode) + - (type == null ? 0 : type.hashCode) + - (message == null ? 0 : message.hashCode); + // ignore: unnecessary_parenthesis + (code == null ? 0 : code!.hashCode) + + (type == null ? 0 : type!.hashCode) + + (message == null ? 0 : message!.hashCode); @override String toString() => 'ApiResponse[code=$code, type=$type, message=$message]'; @@ -57,9 +75,21 @@ class ApiResponse { /// Returns a new [ApiResponse] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static ApiResponse fromJson(dynamic value) { + static ApiResponse? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "ApiResponse[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "ApiResponse[$key]" has a null value in JSON.'); + }); + return true; + }()); + return ApiResponse( code: mapValueOfType(json, r'code'), type: mapValueOfType(json, r'type'), @@ -69,36 +99,50 @@ class ApiResponse { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(ApiResponse.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = ApiResponse.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = ApiResponse.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = ApiResponse.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of ApiResponse-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = ApiResponse.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = ApiResponse.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_of_array_of_number_only.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_of_array_of_number_only.dart index 5525cd19379d..4314803a3ba5 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_of_array_of_number_only.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_of_array_of_number_only.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -24,67 +24,91 @@ class ArrayOfArrayOfNumberOnly { @override int get hashCode => - // ignore: unnecessary_parenthesis - (arrayArrayNumber == null ? 0 : arrayArrayNumber.hashCode); + // ignore: unnecessary_parenthesis + (arrayArrayNumber.hashCode); @override String toString() => 'ArrayOfArrayOfNumberOnly[arrayArrayNumber=$arrayArrayNumber]'; Map toJson() { final json = {}; - if (arrayArrayNumber != null) { json[r'ArrayArrayNumber'] = arrayArrayNumber; - } return json; } /// Returns a new [ArrayOfArrayOfNumberOnly] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static ArrayOfArrayOfNumberOnly fromJson(dynamic value) { + static ArrayOfArrayOfNumberOnly? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "ArrayOfArrayOfNumberOnly[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "ArrayOfArrayOfNumberOnly[$key]" has a null value in JSON.'); + }); + return true; + }()); + return ArrayOfArrayOfNumberOnly( arrayArrayNumber: json[r'ArrayArrayNumber'] is List ? (json[r'ArrayArrayNumber'] as List).map( (e) => e == null ? null : (e as List).cast() - ).toList(growable: false) + ).toList() : null, ); } return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(ArrayOfArrayOfNumberOnly.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = ArrayOfArrayOfNumberOnly.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = ArrayOfArrayOfNumberOnly.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = ArrayOfArrayOfNumberOnly.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of ArrayOfArrayOfNumberOnly-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = ArrayOfArrayOfNumberOnly.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = ArrayOfArrayOfNumberOnly.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_of_number_only.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_of_number_only.dart index 1e23c3ad2d30..8e9d6784f804 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_of_number_only.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_of_number_only.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -24,65 +24,89 @@ class ArrayOfNumberOnly { @override int get hashCode => - // ignore: unnecessary_parenthesis - (arrayNumber == null ? 0 : arrayNumber.hashCode); + // ignore: unnecessary_parenthesis + (arrayNumber.hashCode); @override String toString() => 'ArrayOfNumberOnly[arrayNumber=$arrayNumber]'; Map toJson() { final json = {}; - if (arrayNumber != null) { json[r'ArrayNumber'] = arrayNumber; - } return json; } /// Returns a new [ArrayOfNumberOnly] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static ArrayOfNumberOnly fromJson(dynamic value) { + static ArrayOfNumberOnly? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "ArrayOfNumberOnly[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "ArrayOfNumberOnly[$key]" has a null value in JSON.'); + }); + return true; + }()); + return ArrayOfNumberOnly( arrayNumber: json[r'ArrayNumber'] is List - ? (json[r'ArrayNumber'] as List).cast() - : null, + ? (json[r'ArrayNumber'] as List).cast() + : const [], ); } return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(ArrayOfNumberOnly.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = ArrayOfNumberOnly.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = ArrayOfNumberOnly.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = ArrayOfNumberOnly.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of ArrayOfNumberOnly-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = ArrayOfNumberOnly.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = ArrayOfNumberOnly.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_test.dart index 6ae2096a5650..a914c04ee52a 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_test.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -32,83 +32,103 @@ class ArrayTest { @override int get hashCode => - // ignore: unnecessary_parenthesis - (arrayOfString == null ? 0 : arrayOfString.hashCode) + - (arrayArrayOfInteger == null ? 0 : arrayArrayOfInteger.hashCode) + - (arrayArrayOfModel == null ? 0 : arrayArrayOfModel.hashCode); + // ignore: unnecessary_parenthesis + (arrayOfString.hashCode) + + (arrayArrayOfInteger.hashCode) + + (arrayArrayOfModel.hashCode); @override String toString() => 'ArrayTest[arrayOfString=$arrayOfString, arrayArrayOfInteger=$arrayArrayOfInteger, arrayArrayOfModel=$arrayArrayOfModel]'; Map toJson() { final json = {}; - if (arrayOfString != null) { json[r'array_of_string'] = arrayOfString; - } - if (arrayArrayOfInteger != null) { json[r'array_array_of_integer'] = arrayArrayOfInteger; - } - if (arrayArrayOfModel != null) { json[r'array_array_of_model'] = arrayArrayOfModel; - } return json; } /// Returns a new [ArrayTest] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static ArrayTest fromJson(dynamic value) { + static ArrayTest? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "ArrayTest[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "ArrayTest[$key]" has a null value in JSON.'); + }); + return true; + }()); + return ArrayTest( arrayOfString: json[r'array_of_string'] is List - ? (json[r'array_of_string'] as List).cast() - : null, + ? (json[r'array_of_string'] as List).cast() + : const [], arrayArrayOfInteger: json[r'array_array_of_integer'] is List ? (json[r'array_array_of_integer'] as List).map( (e) => e == null ? null : (e as List).cast() - ).toList(growable: false) + ).toList() : null, arrayArrayOfModel: json[r'array_array_of_model'] is List ? (json[r'array_array_of_model'] as List).map( ReadOnlyFirst.listFromJson(json[r'array_array_of_model']) - ).toList(growable: false) + ).toList() : null, ); } return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(ArrayTest.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = ArrayTest.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = ArrayTest.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = ArrayTest.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of ArrayTest-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = ArrayTest.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = ArrayTest.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/capitalization.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/capitalization.dart index 678bc6f2ea84..3e781d44c727 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/capitalization.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/capitalization.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -21,18 +21,54 @@ class Capitalization { this.ATT_NAME, }); - String smallCamel; - - String capitalCamel; - - String smallSnake; - - String capitalSnake; - - String sCAETHFlowPoints; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? smallCamel; + + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? capitalCamel; + + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? smallSnake; + + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? capitalSnake; + + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? sCAETHFlowPoints; /// Name of the pet - String ATT_NAME; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? ATT_NAME; @override bool operator ==(Object other) => identical(this, other) || other is Capitalization && @@ -45,13 +81,13 @@ class Capitalization { @override int get hashCode => - // ignore: unnecessary_parenthesis - (smallCamel == null ? 0 : smallCamel.hashCode) + - (capitalCamel == null ? 0 : capitalCamel.hashCode) + - (smallSnake == null ? 0 : smallSnake.hashCode) + - (capitalSnake == null ? 0 : capitalSnake.hashCode) + - (sCAETHFlowPoints == null ? 0 : sCAETHFlowPoints.hashCode) + - (ATT_NAME == null ? 0 : ATT_NAME.hashCode); + // ignore: unnecessary_parenthesis + (smallCamel == null ? 0 : smallCamel!.hashCode) + + (capitalCamel == null ? 0 : capitalCamel!.hashCode) + + (smallSnake == null ? 0 : smallSnake!.hashCode) + + (capitalSnake == null ? 0 : capitalSnake!.hashCode) + + (sCAETHFlowPoints == null ? 0 : sCAETHFlowPoints!.hashCode) + + (ATT_NAME == null ? 0 : ATT_NAME!.hashCode); @override String toString() => 'Capitalization[smallCamel=$smallCamel, capitalCamel=$capitalCamel, smallSnake=$smallSnake, capitalSnake=$capitalSnake, sCAETHFlowPoints=$sCAETHFlowPoints, ATT_NAME=$ATT_NAME]'; @@ -82,9 +118,21 @@ class Capitalization { /// Returns a new [Capitalization] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static Capitalization fromJson(dynamic value) { + static Capitalization? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "Capitalization[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "Capitalization[$key]" has a null value in JSON.'); + }); + return true; + }()); + return Capitalization( smallCamel: mapValueOfType(json, r'smallCamel'), capitalCamel: mapValueOfType(json, r'CapitalCamel'), @@ -97,36 +145,50 @@ class Capitalization { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(Capitalization.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = Capitalization.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = Capitalization.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Capitalization.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of Capitalization-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = Capitalization.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Capitalization.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/cat.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/cat.dart index b34fdc7d9a29..f5b639d8e342 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/cat.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/cat.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -13,7 +13,7 @@ part of openapi.api; class Cat { /// Returns a new [Cat] instance. Cat({ - @required this.className, + required this.className, this.color = 'red', this.declawed, }); @@ -22,7 +22,13 @@ class Cat { String color; - bool declawed; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + bool? declawed; @override bool operator ==(Object other) => identical(this, other) || other is Cat && @@ -32,10 +38,10 @@ class Cat { @override int get hashCode => - // ignore: unnecessary_parenthesis - (className == null ? 0 : className.hashCode) + - (color == null ? 0 : color.hashCode) + - (declawed == null ? 0 : declawed.hashCode); + // ignore: unnecessary_parenthesis + (className.hashCode) + + (color.hashCode) + + (declawed == null ? 0 : declawed!.hashCode); @override String toString() => 'Cat[className=$className, color=$color, declawed=$declawed]'; @@ -43,9 +49,7 @@ class Cat { Map toJson() { final json = {}; json[r'className'] = className; - if (color != null) { json[r'color'] = color; - } if (declawed != null) { json[r'declawed'] = declawed; } @@ -55,48 +59,75 @@ class Cat { /// Returns a new [Cat] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static Cat fromJson(dynamic value) { + static Cat? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "Cat[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "Cat[$key]" has a null value in JSON.'); + }); + return true; + }()); + return Cat( - className: mapValueOfType(json, r'className'), - color: mapValueOfType(json, r'color'), + className: mapValueOfType(json, r'className')!, + color: mapValueOfType(json, r'color') ?? 'red', declawed: mapValueOfType(json, r'declawed'), ); } return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(Cat.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = Cat.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = Cat.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Cat.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of Cat-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = Cat.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Cat.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + 'className', + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/cat_all_of.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/cat_all_of.dart index 97bbde44213c..608082b26ad7 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/cat_all_of.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/cat_all_of.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -16,7 +16,13 @@ class CatAllOf { this.declawed, }); - bool declawed; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + bool? declawed; @override bool operator ==(Object other) => identical(this, other) || other is CatAllOf && @@ -24,8 +30,8 @@ class CatAllOf { @override int get hashCode => - // ignore: unnecessary_parenthesis - (declawed == null ? 0 : declawed.hashCode); + // ignore: unnecessary_parenthesis + (declawed == null ? 0 : declawed!.hashCode); @override String toString() => 'CatAllOf[declawed=$declawed]'; @@ -41,9 +47,21 @@ class CatAllOf { /// Returns a new [CatAllOf] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static CatAllOf fromJson(dynamic value) { + static CatAllOf? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "CatAllOf[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "CatAllOf[$key]" has a null value in JSON.'); + }); + return true; + }()); + return CatAllOf( declawed: mapValueOfType(json, r'declawed'), ); @@ -51,36 +69,50 @@ class CatAllOf { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(CatAllOf.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = CatAllOf.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = CatAllOf.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = CatAllOf.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of CatAllOf-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = CatAllOf.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = CatAllOf.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/category.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/category.dart index 294c4f57e9c8..9b77fed5e7cb 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/category.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/category.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -17,7 +17,13 @@ class Category { this.name = 'default-name', }); - int id; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? id; String name; @@ -28,9 +34,9 @@ class Category { @override int get hashCode => - // ignore: unnecessary_parenthesis - (id == null ? 0 : id.hashCode) + - (name == null ? 0 : name.hashCode); + // ignore: unnecessary_parenthesis + (id == null ? 0 : id!.hashCode) + + (name.hashCode); @override String toString() => 'Category[id=$id, name=$name]'; @@ -47,47 +53,74 @@ class Category { /// Returns a new [Category] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static Category fromJson(dynamic value) { + static Category? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "Category[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "Category[$key]" has a null value in JSON.'); + }); + return true; + }()); + return Category( id: mapValueOfType(json, r'id'), - name: mapValueOfType(json, r'name'), + name: mapValueOfType(json, r'name')!, ); } return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(Category.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = Category.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = Category.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Category.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of Category-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = Category.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Category.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + 'name', + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/class_model.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/class_model.dart index 4736fb60ca8e..8335e5810968 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/class_model.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/class_model.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -16,7 +16,13 @@ class ClassModel { this.class_, }); - String class_; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? class_; @override bool operator ==(Object other) => identical(this, other) || other is ClassModel && @@ -24,8 +30,8 @@ class ClassModel { @override int get hashCode => - // ignore: unnecessary_parenthesis - (class_ == null ? 0 : class_.hashCode); + // ignore: unnecessary_parenthesis + (class_ == null ? 0 : class_!.hashCode); @override String toString() => 'ClassModel[class_=$class_]'; @@ -41,9 +47,21 @@ class ClassModel { /// Returns a new [ClassModel] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static ClassModel fromJson(dynamic value) { + static ClassModel? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "ClassModel[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "ClassModel[$key]" has a null value in JSON.'); + }); + return true; + }()); + return ClassModel( class_: mapValueOfType(json, r'_class'), ); @@ -51,36 +69,50 @@ class ClassModel { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(ClassModel.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = ClassModel.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = ClassModel.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = ClassModel.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of ClassModel-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = ClassModel.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = ClassModel.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/deprecated_object.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/deprecated_object.dart index a84c7155c8ad..b8a5b443cc7e 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/deprecated_object.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/deprecated_object.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -16,7 +16,13 @@ class DeprecatedObject { this.name, }); - String name; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? name; @override bool operator ==(Object other) => identical(this, other) || other is DeprecatedObject && @@ -24,8 +30,8 @@ class DeprecatedObject { @override int get hashCode => - // ignore: unnecessary_parenthesis - (name == null ? 0 : name.hashCode); + // ignore: unnecessary_parenthesis + (name == null ? 0 : name!.hashCode); @override String toString() => 'DeprecatedObject[name=$name]'; @@ -41,9 +47,21 @@ class DeprecatedObject { /// Returns a new [DeprecatedObject] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static DeprecatedObject fromJson(dynamic value) { + static DeprecatedObject? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "DeprecatedObject[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "DeprecatedObject[$key]" has a null value in JSON.'); + }); + return true; + }()); + return DeprecatedObject( name: mapValueOfType(json, r'name'), ); @@ -51,36 +69,50 @@ class DeprecatedObject { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(DeprecatedObject.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = DeprecatedObject.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = DeprecatedObject.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = DeprecatedObject.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of DeprecatedObject-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = DeprecatedObject.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = DeprecatedObject.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/dog.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/dog.dart index 68d592bef451..8ec20b96c81a 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/dog.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/dog.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -13,7 +13,7 @@ part of openapi.api; class Dog { /// Returns a new [Dog] instance. Dog({ - @required this.className, + required this.className, this.color = 'red', this.breed, }); @@ -22,7 +22,13 @@ class Dog { String color; - String breed; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? breed; @override bool operator ==(Object other) => identical(this, other) || other is Dog && @@ -32,10 +38,10 @@ class Dog { @override int get hashCode => - // ignore: unnecessary_parenthesis - (className == null ? 0 : className.hashCode) + - (color == null ? 0 : color.hashCode) + - (breed == null ? 0 : breed.hashCode); + // ignore: unnecessary_parenthesis + (className.hashCode) + + (color.hashCode) + + (breed == null ? 0 : breed!.hashCode); @override String toString() => 'Dog[className=$className, color=$color, breed=$breed]'; @@ -43,9 +49,7 @@ class Dog { Map toJson() { final json = {}; json[r'className'] = className; - if (color != null) { json[r'color'] = color; - } if (breed != null) { json[r'breed'] = breed; } @@ -55,48 +59,75 @@ class Dog { /// Returns a new [Dog] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static Dog fromJson(dynamic value) { + static Dog? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "Dog[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "Dog[$key]" has a null value in JSON.'); + }); + return true; + }()); + return Dog( - className: mapValueOfType(json, r'className'), - color: mapValueOfType(json, r'color'), + className: mapValueOfType(json, r'className')!, + color: mapValueOfType(json, r'color') ?? 'red', breed: mapValueOfType(json, r'breed'), ); } return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(Dog.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = Dog.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = Dog.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Dog.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of Dog-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = Dog.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Dog.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + 'className', + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/dog_all_of.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/dog_all_of.dart index a4e2559cd668..03d52a6cb2f9 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/dog_all_of.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/dog_all_of.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -16,7 +16,13 @@ class DogAllOf { this.breed, }); - String breed; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? breed; @override bool operator ==(Object other) => identical(this, other) || other is DogAllOf && @@ -24,8 +30,8 @@ class DogAllOf { @override int get hashCode => - // ignore: unnecessary_parenthesis - (breed == null ? 0 : breed.hashCode); + // ignore: unnecessary_parenthesis + (breed == null ? 0 : breed!.hashCode); @override String toString() => 'DogAllOf[breed=$breed]'; @@ -41,9 +47,21 @@ class DogAllOf { /// Returns a new [DogAllOf] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static DogAllOf fromJson(dynamic value) { + static DogAllOf? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "DogAllOf[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "DogAllOf[$key]" has a null value in JSON.'); + }); + return true; + }()); + return DogAllOf( breed: mapValueOfType(json, r'breed'), ); @@ -51,36 +69,50 @@ class DogAllOf { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(DogAllOf.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = DogAllOf.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = DogAllOf.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = DogAllOf.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of DogAllOf-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = DogAllOf.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = DogAllOf.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_arrays.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_arrays.dart index 96ff43d00383..ad8bff240a14 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_arrays.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_arrays.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -17,7 +17,7 @@ class EnumArrays { this.arrayEnum = const [], }); - EnumArraysJustSymbolEnum justSymbol; + EnumArraysJustSymbolEnum? justSymbol; List arrayEnum; @@ -28,9 +28,9 @@ class EnumArrays { @override int get hashCode => - // ignore: unnecessary_parenthesis - (justSymbol == null ? 0 : justSymbol.hashCode) + - (arrayEnum == null ? 0 : arrayEnum.hashCode); + // ignore: unnecessary_parenthesis + (justSymbol == null ? 0 : justSymbol!.hashCode) + + (arrayEnum.hashCode); @override String toString() => 'EnumArrays[justSymbol=$justSymbol, arrayEnum=$arrayEnum]'; @@ -40,57 +40,81 @@ class EnumArrays { if (justSymbol != null) { json[r'just_symbol'] = justSymbol; } - if (arrayEnum != null) { json[r'array_enum'] = arrayEnum; - } return json; } /// Returns a new [EnumArrays] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static EnumArrays fromJson(dynamic value) { + static EnumArrays? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "EnumArrays[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "EnumArrays[$key]" has a null value in JSON.'); + }); + return true; + }()); + return EnumArrays( justSymbol: EnumArraysJustSymbolEnum.fromJson(json[r'just_symbol']), - arrayEnum: EnumArraysArrayEnumEnum.listFromJson(json[r'array_enum']), + arrayEnum: EnumArraysArrayEnumEnum.listFromJson(json[r'array_enum']) ?? const [], ); } return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(EnumArrays.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = EnumArrays.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = EnumArrays.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = EnumArrays.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of EnumArrays-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = EnumArrays.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = EnumArrays.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } @@ -102,7 +126,7 @@ class EnumArraysJustSymbolEnum { final String value; @override - String toString() => value ?? ''; + String toString() => value; String toJson() => value; @@ -115,13 +139,20 @@ class EnumArraysJustSymbolEnum { dollar, ]; - static EnumArraysJustSymbolEnum fromJson(dynamic value) => - EnumArraysJustSymbolEnumTypeTransformer().decode(value); + static EnumArraysJustSymbolEnum? fromJson(dynamic value) => EnumArraysJustSymbolEnumTypeTransformer().decode(value); - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(EnumArraysJustSymbolEnum.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = EnumArraysJustSymbolEnum.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } } /// Transformation class that can [encode] an instance of [EnumArraysJustSymbolEnum] to String, @@ -141,13 +172,13 @@ class EnumArraysJustSymbolEnumTypeTransformer { /// /// The [allowNull] is very handy when an API changes and a new enum value is added or removed, /// and users are still using an old app with the old code. - EnumArraysJustSymbolEnum decode(dynamic data, {bool allowNull}) { + EnumArraysJustSymbolEnum? decode(dynamic data, {bool allowNull = true}) { if (data != null) { switch (data.toString()) { case r'>=': return EnumArraysJustSymbolEnum.greaterThanEqual; case r'$': return EnumArraysJustSymbolEnum.dollar; default: - if (allowNull == false) { + if (!allowNull) { throw ArgumentError('Unknown enum value to decode: $data'); } } @@ -156,7 +187,7 @@ class EnumArraysJustSymbolEnumTypeTransformer { } /// Singleton [EnumArraysJustSymbolEnumTypeTransformer] instance. - static EnumArraysJustSymbolEnumTypeTransformer _instance; + static EnumArraysJustSymbolEnumTypeTransformer? _instance; } @@ -169,7 +200,7 @@ class EnumArraysArrayEnumEnum { final String value; @override - String toString() => value ?? ''; + String toString() => value; String toJson() => value; @@ -182,13 +213,20 @@ class EnumArraysArrayEnumEnum { crab, ]; - static EnumArraysArrayEnumEnum fromJson(dynamic value) => - EnumArraysArrayEnumEnumTypeTransformer().decode(value); + static EnumArraysArrayEnumEnum? fromJson(dynamic value) => EnumArraysArrayEnumEnumTypeTransformer().decode(value); - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(EnumArraysArrayEnumEnum.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = EnumArraysArrayEnumEnum.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } } /// Transformation class that can [encode] an instance of [EnumArraysArrayEnumEnum] to String, @@ -208,13 +246,13 @@ class EnumArraysArrayEnumEnumTypeTransformer { /// /// The [allowNull] is very handy when an API changes and a new enum value is added or removed, /// and users are still using an old app with the old code. - EnumArraysArrayEnumEnum decode(dynamic data, {bool allowNull}) { + EnumArraysArrayEnumEnum? decode(dynamic data, {bool allowNull = true}) { if (data != null) { switch (data.toString()) { case r'fish': return EnumArraysArrayEnumEnum.fish; case r'crab': return EnumArraysArrayEnumEnum.crab; default: - if (allowNull == false) { + if (!allowNull) { throw ArgumentError('Unknown enum value to decode: $data'); } } @@ -223,7 +261,7 @@ class EnumArraysArrayEnumEnumTypeTransformer { } /// Singleton [EnumArraysArrayEnumEnumTypeTransformer] instance. - static EnumArraysArrayEnumEnumTypeTransformer _instance; + static EnumArraysArrayEnumEnumTypeTransformer? _instance; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_class.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_class.dart index e50e9471eacb..ad0fee194896 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_class.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_class.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -19,7 +19,7 @@ class EnumClass { final String value; @override - String toString() => value ?? ''; + String toString() => value; String toJson() => value; @@ -34,13 +34,20 @@ class EnumClass { leftParenthesisXyzRightParenthesis, ]; - static EnumClass fromJson(dynamic value) => - EnumClassTypeTransformer().decode(value); + static EnumClass? fromJson(dynamic value) => EnumClassTypeTransformer().decode(value); - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(EnumClass.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = EnumClass.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } } /// Transformation class that can [encode] an instance of [EnumClass] to String, @@ -60,14 +67,14 @@ class EnumClassTypeTransformer { /// /// The [allowNull] is very handy when an API changes and a new enum value is added or removed, /// and users are still using an old app with the old code. - EnumClass decode(dynamic data, {bool allowNull}) { + EnumClass? decode(dynamic data, {bool allowNull = true}) { if (data != null) { switch (data.toString()) { case r'_abc': return EnumClass.abc; case r'-efg': return EnumClass.efg; case r'(xyz)': return EnumClass.leftParenthesisXyzRightParenthesis; default: - if (allowNull == false) { + if (!allowNull) { throw ArgumentError('Unknown enum value to decode: $data'); } } @@ -76,6 +83,6 @@ class EnumClassTypeTransformer { } /// Singleton [EnumClassTypeTransformer] instance. - static EnumClassTypeTransformer _instance; + static EnumClassTypeTransformer? _instance; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_test.dart index ee1a8aff9f3c..06ff55540f79 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_test.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -14,7 +14,7 @@ class EnumTest { /// Returns a new [EnumTest] instance. EnumTest({ this.enumString, - @required this.enumStringRequired, + required this.enumStringRequired, this.enumInteger, this.enumNumber, this.outerEnum, @@ -23,21 +23,39 @@ class EnumTest { this.outerEnumIntegerDefaultValue, }); - EnumTestEnumStringEnum enumString; + EnumTestEnumStringEnum? enumString; EnumTestEnumStringRequiredEnum enumStringRequired; - EnumTestEnumIntegerEnum enumInteger; + EnumTestEnumIntegerEnum? enumInteger; - EnumTestEnumNumberEnum enumNumber; + EnumTestEnumNumberEnum? enumNumber; - OuterEnum outerEnum; + OuterEnum? outerEnum; - OuterEnumInteger outerEnumInteger; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + OuterEnumInteger? outerEnumInteger; - OuterEnumDefaultValue outerEnumDefaultValue; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + OuterEnumDefaultValue? outerEnumDefaultValue; - OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + OuterEnumIntegerDefaultValue? outerEnumIntegerDefaultValue; @override bool operator ==(Object other) => identical(this, other) || other is EnumTest && @@ -52,15 +70,15 @@ class EnumTest { @override int get hashCode => - // ignore: unnecessary_parenthesis - (enumString == null ? 0 : enumString.hashCode) + - (enumStringRequired == null ? 0 : enumStringRequired.hashCode) + - (enumInteger == null ? 0 : enumInteger.hashCode) + - (enumNumber == null ? 0 : enumNumber.hashCode) + - (outerEnum == null ? 0 : outerEnum.hashCode) + - (outerEnumInteger == null ? 0 : outerEnumInteger.hashCode) + - (outerEnumDefaultValue == null ? 0 : outerEnumDefaultValue.hashCode) + - (outerEnumIntegerDefaultValue == null ? 0 : outerEnumIntegerDefaultValue.hashCode); + // ignore: unnecessary_parenthesis + (enumString == null ? 0 : enumString!.hashCode) + + (enumStringRequired.hashCode) + + (enumInteger == null ? 0 : enumInteger!.hashCode) + + (enumNumber == null ? 0 : enumNumber!.hashCode) + + (outerEnum == null ? 0 : outerEnum!.hashCode) + + (outerEnumInteger == null ? 0 : outerEnumInteger!.hashCode) + + (outerEnumDefaultValue == null ? 0 : outerEnumDefaultValue!.hashCode) + + (outerEnumIntegerDefaultValue == null ? 0 : outerEnumIntegerDefaultValue!.hashCode); @override String toString() => 'EnumTest[enumString=$enumString, enumStringRequired=$enumStringRequired, enumInteger=$enumInteger, enumNumber=$enumNumber, outerEnum=$outerEnum, outerEnumInteger=$outerEnumInteger, outerEnumDefaultValue=$outerEnumDefaultValue, outerEnumIntegerDefaultValue=$outerEnumIntegerDefaultValue]'; @@ -95,12 +113,24 @@ class EnumTest { /// Returns a new [EnumTest] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static EnumTest fromJson(dynamic value) { + static EnumTest? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "EnumTest[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "EnumTest[$key]" has a null value in JSON.'); + }); + return true; + }()); + return EnumTest( enumString: EnumTestEnumStringEnum.fromJson(json[r'enum_string']), - enumStringRequired: EnumTestEnumStringRequiredEnum.fromJson(json[r'enum_string_required']), + enumStringRequired: EnumTestEnumStringRequiredEnum.fromJson(json[r'enum_string_required'])!, enumInteger: EnumTestEnumIntegerEnum.fromJson(json[r'enum_integer']), enumNumber: EnumTestEnumNumberEnum.fromJson(json[r'enum_number']), outerEnum: OuterEnum.fromJson(json[r'outerEnum']), @@ -112,37 +142,52 @@ class EnumTest { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(EnumTest.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = EnumTest.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = EnumTest.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = EnumTest.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of EnumTest-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = EnumTest.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = EnumTest.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + 'enum_string_required', + }; } @@ -154,7 +199,7 @@ class EnumTestEnumStringEnum { final String value; @override - String toString() => value ?? ''; + String toString() => value; String toJson() => value; @@ -169,13 +214,20 @@ class EnumTestEnumStringEnum { empty, ]; - static EnumTestEnumStringEnum fromJson(dynamic value) => - EnumTestEnumStringEnumTypeTransformer().decode(value); + static EnumTestEnumStringEnum? fromJson(dynamic value) => EnumTestEnumStringEnumTypeTransformer().decode(value); - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(EnumTestEnumStringEnum.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = EnumTestEnumStringEnum.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } } /// Transformation class that can [encode] an instance of [EnumTestEnumStringEnum] to String, @@ -195,14 +247,14 @@ class EnumTestEnumStringEnumTypeTransformer { /// /// The [allowNull] is very handy when an API changes and a new enum value is added or removed, /// and users are still using an old app with the old code. - EnumTestEnumStringEnum decode(dynamic data, {bool allowNull}) { + EnumTestEnumStringEnum? decode(dynamic data, {bool allowNull = true}) { if (data != null) { switch (data.toString()) { case r'UPPER': return EnumTestEnumStringEnum.UPPER; case r'lower': return EnumTestEnumStringEnum.lower; case r'': return EnumTestEnumStringEnum.empty; default: - if (allowNull == false) { + if (!allowNull) { throw ArgumentError('Unknown enum value to decode: $data'); } } @@ -211,7 +263,7 @@ class EnumTestEnumStringEnumTypeTransformer { } /// Singleton [EnumTestEnumStringEnumTypeTransformer] instance. - static EnumTestEnumStringEnumTypeTransformer _instance; + static EnumTestEnumStringEnumTypeTransformer? _instance; } @@ -224,7 +276,7 @@ class EnumTestEnumStringRequiredEnum { final String value; @override - String toString() => value ?? ''; + String toString() => value; String toJson() => value; @@ -239,13 +291,20 @@ class EnumTestEnumStringRequiredEnum { empty, ]; - static EnumTestEnumStringRequiredEnum fromJson(dynamic value) => - EnumTestEnumStringRequiredEnumTypeTransformer().decode(value); + static EnumTestEnumStringRequiredEnum? fromJson(dynamic value) => EnumTestEnumStringRequiredEnumTypeTransformer().decode(value); - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(EnumTestEnumStringRequiredEnum.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = EnumTestEnumStringRequiredEnum.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } } /// Transformation class that can [encode] an instance of [EnumTestEnumStringRequiredEnum] to String, @@ -265,14 +324,14 @@ class EnumTestEnumStringRequiredEnumTypeTransformer { /// /// The [allowNull] is very handy when an API changes and a new enum value is added or removed, /// and users are still using an old app with the old code. - EnumTestEnumStringRequiredEnum decode(dynamic data, {bool allowNull}) { + EnumTestEnumStringRequiredEnum? decode(dynamic data, {bool allowNull = true}) { if (data != null) { switch (data.toString()) { case r'UPPER': return EnumTestEnumStringRequiredEnum.UPPER; case r'lower': return EnumTestEnumStringRequiredEnum.lower; case r'': return EnumTestEnumStringRequiredEnum.empty; default: - if (allowNull == false) { + if (!allowNull) { throw ArgumentError('Unknown enum value to decode: $data'); } } @@ -281,7 +340,7 @@ class EnumTestEnumStringRequiredEnumTypeTransformer { } /// Singleton [EnumTestEnumStringRequiredEnumTypeTransformer] instance. - static EnumTestEnumStringRequiredEnumTypeTransformer _instance; + static EnumTestEnumStringRequiredEnumTypeTransformer? _instance; } @@ -294,7 +353,7 @@ class EnumTestEnumIntegerEnum { final int value; @override - String toString() => value == null ? '' : value.toString(); + String toString() => value.toString(); int toJson() => value; @@ -307,13 +366,20 @@ class EnumTestEnumIntegerEnum { numberNegative1, ]; - static EnumTestEnumIntegerEnum fromJson(dynamic value) => - EnumTestEnumIntegerEnumTypeTransformer().decode(value); + static EnumTestEnumIntegerEnum? fromJson(dynamic value) => EnumTestEnumIntegerEnumTypeTransformer().decode(value); - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(EnumTestEnumIntegerEnum.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = EnumTestEnumIntegerEnum.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } } /// Transformation class that can [encode] an instance of [EnumTestEnumIntegerEnum] to int, @@ -333,13 +399,13 @@ class EnumTestEnumIntegerEnumTypeTransformer { /// /// The [allowNull] is very handy when an API changes and a new enum value is added or removed, /// and users are still using an old app with the old code. - EnumTestEnumIntegerEnum decode(dynamic data, {bool allowNull}) { + EnumTestEnumIntegerEnum? decode(dynamic data, {bool allowNull = true}) { if (data != null) { switch (data.toString()) { case 1: return EnumTestEnumIntegerEnum.number1; case -1: return EnumTestEnumIntegerEnum.numberNegative1; default: - if (allowNull == false) { + if (!allowNull) { throw ArgumentError('Unknown enum value to decode: $data'); } } @@ -348,7 +414,7 @@ class EnumTestEnumIntegerEnumTypeTransformer { } /// Singleton [EnumTestEnumIntegerEnumTypeTransformer] instance. - static EnumTestEnumIntegerEnumTypeTransformer _instance; + static EnumTestEnumIntegerEnumTypeTransformer? _instance; } @@ -361,7 +427,7 @@ class EnumTestEnumNumberEnum { final double value; @override - String toString() => value == null ? '' : value.toString(); + String toString() => value.toString(); double toJson() => value; @@ -374,13 +440,20 @@ class EnumTestEnumNumberEnum { numberNegative1Period2, ]; - static EnumTestEnumNumberEnum fromJson(dynamic value) => - EnumTestEnumNumberEnumTypeTransformer().decode(value); + static EnumTestEnumNumberEnum? fromJson(dynamic value) => EnumTestEnumNumberEnumTypeTransformer().decode(value); - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(EnumTestEnumNumberEnum.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = EnumTestEnumNumberEnum.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } } /// Transformation class that can [encode] an instance of [EnumTestEnumNumberEnum] to double, @@ -400,13 +473,13 @@ class EnumTestEnumNumberEnumTypeTransformer { /// /// The [allowNull] is very handy when an API changes and a new enum value is added or removed, /// and users are still using an old app with the old code. - EnumTestEnumNumberEnum decode(dynamic data, {bool allowNull}) { + EnumTestEnumNumberEnum? decode(dynamic data, {bool allowNull = true}) { if (data != null) { switch (data.toString()) { case '1.1': return EnumTestEnumNumberEnum.number1Period1; case '-1.2': return EnumTestEnumNumberEnum.numberNegative1Period2; default: - if (allowNull == false) { + if (!allowNull) { throw ArgumentError('Unknown enum value to decode: $data'); } } @@ -415,7 +488,7 @@ class EnumTestEnumNumberEnumTypeTransformer { } /// Singleton [EnumTestEnumNumberEnumTypeTransformer] instance. - static EnumTestEnumNumberEnumTypeTransformer _instance; + static EnumTestEnumNumberEnumTypeTransformer? _instance; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/file_schema_test_class.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/file_schema_test_class.dart index 82decacafc7f..0f53a5ed1f92 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/file_schema_test_class.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/file_schema_test_class.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -17,7 +17,13 @@ class FileSchemaTestClass { this.files = const [], }); - ModelFile file; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + ModelFile? file; List files; @@ -28,9 +34,9 @@ class FileSchemaTestClass { @override int get hashCode => - // ignore: unnecessary_parenthesis - (file == null ? 0 : file.hashCode) + - (files == null ? 0 : files.hashCode); + // ignore: unnecessary_parenthesis + (file == null ? 0 : file!.hashCode) + + (files.hashCode); @override String toString() => 'FileSchemaTestClass[file=$file, files=$files]'; @@ -40,56 +46,80 @@ class FileSchemaTestClass { if (file != null) { json[r'file'] = file; } - if (files != null) { json[r'files'] = files; - } return json; } /// Returns a new [FileSchemaTestClass] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static FileSchemaTestClass fromJson(dynamic value) { + static FileSchemaTestClass? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "FileSchemaTestClass[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "FileSchemaTestClass[$key]" has a null value in JSON.'); + }); + return true; + }()); + return FileSchemaTestClass( file: ModelFile.fromJson(json[r'file']), - files: ModelFile.listFromJson(json[r'files']), + files: ModelFile.listFromJson(json[r'files']) ?? const [], ); } return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(FileSchemaTestClass.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = FileSchemaTestClass.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = FileSchemaTestClass.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = FileSchemaTestClass.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of FileSchemaTestClass-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = FileSchemaTestClass.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = FileSchemaTestClass.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/foo.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/foo.dart index fe73d2705506..4fd3f08d59a8 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/foo.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/foo.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -24,63 +24,87 @@ class Foo { @override int get hashCode => - // ignore: unnecessary_parenthesis - (bar == null ? 0 : bar.hashCode); + // ignore: unnecessary_parenthesis + (bar.hashCode); @override String toString() => 'Foo[bar=$bar]'; Map toJson() { final json = {}; - if (bar != null) { json[r'bar'] = bar; - } return json; } /// Returns a new [Foo] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static Foo fromJson(dynamic value) { + static Foo? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "Foo[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "Foo[$key]" has a null value in JSON.'); + }); + return true; + }()); + return Foo( - bar: mapValueOfType(json, r'bar'), + bar: mapValueOfType(json, r'bar') ?? 'bar', ); } return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(Foo.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = Foo.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = Foo.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Foo.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of Foo-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = Foo.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Foo.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/format_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/format_test.dart index 978a67132264..48f039432af4 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/format_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/format_test.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -16,64 +16,136 @@ class FormatTest { this.integer, this.int32, this.int64, - @required this.number, + required this.number, this.float, this.double_, this.decimal, this.string, - @required this.byte, + required this.byte, this.binary, - @required this.date, + required this.date, this.dateTime, this.uuid, - @required this.password, + required this.password, this.patternWithDigits, this.patternWithDigitsAndDelimiter, }); - // minimum: 10 - // maximum: 100 - int integer; + /// Minimum value: 10 + /// Maximum value: 100 + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? integer; - // minimum: 20 - // maximum: 200 - int int32; + /// Minimum value: 20 + /// Maximum value: 200 + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? int32; - int int64; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? int64; - // minimum: 32.1 - // maximum: 543.2 + /// Minimum value: 32.1 + /// Maximum value: 543.2 num number; - // minimum: 54.3 - // maximum: 987.6 - double float; + /// Minimum value: 54.3 + /// Maximum value: 987.6 + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + double? float; - // minimum: 67.8 - // maximum: 123.4 - double double_; + /// Minimum value: 67.8 + /// Maximum value: 123.4 + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + double? double_; - double decimal; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + double? decimal; - String string; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? string; String byte; - MultipartFile binary; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + MultipartFile? binary; DateTime date; - DateTime dateTime; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + DateTime? dateTime; - String uuid; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? uuid; String password; /// A string that is a 10 digit number. Can have leading zeros. - String patternWithDigits; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? patternWithDigits; /// A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. - String patternWithDigitsAndDelimiter; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? patternWithDigitsAndDelimiter; @override bool operator ==(Object other) => identical(this, other) || other is FormatTest && @@ -96,23 +168,23 @@ class FormatTest { @override int get hashCode => - // ignore: unnecessary_parenthesis - (integer == null ? 0 : integer.hashCode) + - (int32 == null ? 0 : int32.hashCode) + - (int64 == null ? 0 : int64.hashCode) + - (number == null ? 0 : number.hashCode) + - (float == null ? 0 : float.hashCode) + - (double_ == null ? 0 : double_.hashCode) + - (decimal == null ? 0 : decimal.hashCode) + - (string == null ? 0 : string.hashCode) + - (byte == null ? 0 : byte.hashCode) + - (binary == null ? 0 : binary.hashCode) + - (date == null ? 0 : date.hashCode) + - (dateTime == null ? 0 : dateTime.hashCode) + - (uuid == null ? 0 : uuid.hashCode) + - (password == null ? 0 : password.hashCode) + - (patternWithDigits == null ? 0 : patternWithDigits.hashCode) + - (patternWithDigitsAndDelimiter == null ? 0 : patternWithDigitsAndDelimiter.hashCode); + // ignore: unnecessary_parenthesis + (integer == null ? 0 : integer!.hashCode) + + (int32 == null ? 0 : int32!.hashCode) + + (int64 == null ? 0 : int64!.hashCode) + + (number.hashCode) + + (float == null ? 0 : float!.hashCode) + + (double_ == null ? 0 : double_!.hashCode) + + (decimal == null ? 0 : decimal!.hashCode) + + (string == null ? 0 : string!.hashCode) + + (byte.hashCode) + + (binary == null ? 0 : binary!.hashCode) + + (date.hashCode) + + (dateTime == null ? 0 : dateTime!.hashCode) + + (uuid == null ? 0 : uuid!.hashCode) + + (password.hashCode) + + (patternWithDigits == null ? 0 : patternWithDigits!.hashCode) + + (patternWithDigitsAndDelimiter == null ? 0 : patternWithDigitsAndDelimiter!.hashCode); @override String toString() => 'FormatTest[integer=$integer, int32=$int32, int64=$int64, number=$number, float=$float, double_=$double_, decimal=$decimal, string=$string, byte=$byte, binary=$binary, date=$date, dateTime=$dateTime, uuid=$uuid, password=$password, patternWithDigits=$patternWithDigits, patternWithDigitsAndDelimiter=$patternWithDigitsAndDelimiter]'; @@ -147,7 +219,7 @@ class FormatTest { } json[r'date'] = _dateFormatter.format(date.toUtc()); if (dateTime != null) { - json[r'dateTime'] = dateTime.toUtc().toIso8601String(); + json[r'dateTime'] = dateTime!.toUtc().toIso8601String(); } if (uuid != null) { json[r'uuid'] = uuid; @@ -165,26 +237,38 @@ class FormatTest { /// Returns a new [FormatTest] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static FormatTest fromJson(dynamic value) { + static FormatTest? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "FormatTest[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "FormatTest[$key]" has a null value in JSON.'); + }); + return true; + }()); + return FormatTest( integer: mapValueOfType(json, r'integer'), int32: mapValueOfType(json, r'int32'), int64: mapValueOfType(json, r'int64'), number: json[r'number'] == null - ? null - : num.parse(json[r'number'].toString()), + ? null + : num.parse(json[r'number'].toString()), float: mapValueOfType(json, r'float'), double_: mapValueOfType(json, r'double'), decimal: mapValueOfType(json, r'decimal'), string: mapValueOfType(json, r'string'), - byte: mapValueOfType(json, r'byte'), + byte: mapValueOfType(json, r'byte')!, binary: null, // No support for decoding binary content from JSON - date: mapDateTime(json, r'date', ''), + date: mapDateTime(json, r'date', '')!, dateTime: mapDateTime(json, r'dateTime', ''), uuid: mapValueOfType(json, r'uuid'), - password: mapValueOfType(json, r'password'), + password: mapValueOfType(json, r'password')!, patternWithDigits: mapValueOfType(json, r'pattern_with_digits'), patternWithDigitsAndDelimiter: mapValueOfType(json, r'pattern_with_digits_and_delimiter'), ); @@ -192,36 +276,54 @@ class FormatTest { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(FormatTest.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = FormatTest.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = FormatTest.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = FormatTest.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of FormatTest-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = FormatTest.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = FormatTest.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + 'number', + 'byte', + 'date', + 'password', + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/has_only_read_only.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/has_only_read_only.dart index c827adf295ec..8d6811c7d9b2 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/has_only_read_only.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/has_only_read_only.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -17,9 +17,21 @@ class HasOnlyReadOnly { this.foo, }); - String bar; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? bar; - String foo; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? foo; @override bool operator ==(Object other) => identical(this, other) || other is HasOnlyReadOnly && @@ -28,9 +40,9 @@ class HasOnlyReadOnly { @override int get hashCode => - // ignore: unnecessary_parenthesis - (bar == null ? 0 : bar.hashCode) + - (foo == null ? 0 : foo.hashCode); + // ignore: unnecessary_parenthesis + (bar == null ? 0 : bar!.hashCode) + + (foo == null ? 0 : foo!.hashCode); @override String toString() => 'HasOnlyReadOnly[bar=$bar, foo=$foo]'; @@ -49,9 +61,21 @@ class HasOnlyReadOnly { /// Returns a new [HasOnlyReadOnly] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static HasOnlyReadOnly fromJson(dynamic value) { + static HasOnlyReadOnly? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "HasOnlyReadOnly[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "HasOnlyReadOnly[$key]" has a null value in JSON.'); + }); + return true; + }()); + return HasOnlyReadOnly( bar: mapValueOfType(json, r'bar'), foo: mapValueOfType(json, r'foo'), @@ -60,36 +84,50 @@ class HasOnlyReadOnly { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(HasOnlyReadOnly.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = HasOnlyReadOnly.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = HasOnlyReadOnly.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = HasOnlyReadOnly.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of HasOnlyReadOnly-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = HasOnlyReadOnly.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = HasOnlyReadOnly.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/health_check_result.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/health_check_result.dart index 52359ee4003e..94c1561bd548 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/health_check_result.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/health_check_result.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -16,7 +16,7 @@ class HealthCheckResult { this.nullableMessage, }); - String nullableMessage; + String? nullableMessage; @override bool operator ==(Object other) => identical(this, other) || other is HealthCheckResult && @@ -24,8 +24,8 @@ class HealthCheckResult { @override int get hashCode => - // ignore: unnecessary_parenthesis - (nullableMessage == null ? 0 : nullableMessage.hashCode); + // ignore: unnecessary_parenthesis + (nullableMessage == null ? 0 : nullableMessage!.hashCode); @override String toString() => 'HealthCheckResult[nullableMessage=$nullableMessage]'; @@ -41,9 +41,21 @@ class HealthCheckResult { /// Returns a new [HealthCheckResult] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static HealthCheckResult fromJson(dynamic value) { + static HealthCheckResult? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "HealthCheckResult[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "HealthCheckResult[$key]" has a null value in JSON.'); + }); + return true; + }()); + return HealthCheckResult( nullableMessage: mapValueOfType(json, r'NullableMessage'), ); @@ -51,36 +63,50 @@ class HealthCheckResult { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(HealthCheckResult.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = HealthCheckResult.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = HealthCheckResult.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = HealthCheckResult.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of HealthCheckResult-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = HealthCheckResult.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = HealthCheckResult.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_response_default.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_response_default.dart index 12ac601d7e3a..d66b3546637a 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_response_default.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_response_default.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -16,7 +16,13 @@ class InlineResponseDefault { this.string, }); - Foo string; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + Foo? string; @override bool operator ==(Object other) => identical(this, other) || other is InlineResponseDefault && @@ -24,8 +30,8 @@ class InlineResponseDefault { @override int get hashCode => - // ignore: unnecessary_parenthesis - (string == null ? 0 : string.hashCode); + // ignore: unnecessary_parenthesis + (string == null ? 0 : string!.hashCode); @override String toString() => 'InlineResponseDefault[string=$string]'; @@ -41,9 +47,21 @@ class InlineResponseDefault { /// Returns a new [InlineResponseDefault] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static InlineResponseDefault fromJson(dynamic value) { + static InlineResponseDefault? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "InlineResponseDefault[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "InlineResponseDefault[$key]" has a null value in JSON.'); + }); + return true; + }()); + return InlineResponseDefault( string: Foo.fromJson(json[r'string']), ); @@ -51,36 +69,50 @@ class InlineResponseDefault { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(InlineResponseDefault.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = InlineResponseDefault.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = InlineResponseDefault.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = InlineResponseDefault.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of InlineResponseDefault-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = InlineResponseDefault.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = InlineResponseDefault.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/map_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/map_test.dart index cbb3f1982522..5afcb48e86fa 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/map_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/map_test.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -36,79 +36,97 @@ class MapTest { @override int get hashCode => - // ignore: unnecessary_parenthesis - (mapMapOfString == null ? 0 : mapMapOfString.hashCode) + - (mapOfEnumString == null ? 0 : mapOfEnumString.hashCode) + - (directMap == null ? 0 : directMap.hashCode) + - (indirectMap == null ? 0 : indirectMap.hashCode); + // ignore: unnecessary_parenthesis + (mapMapOfString.hashCode) + + (mapOfEnumString.hashCode) + + (directMap.hashCode) + + (indirectMap.hashCode); @override String toString() => 'MapTest[mapMapOfString=$mapMapOfString, mapOfEnumString=$mapOfEnumString, directMap=$directMap, indirectMap=$indirectMap]'; Map toJson() { final json = {}; - if (mapMapOfString != null) { json[r'map_map_of_string'] = mapMapOfString; - } - if (mapOfEnumString != null) { json[r'map_of_enum_string'] = mapOfEnumString; - } - if (directMap != null) { json[r'direct_map'] = directMap; - } - if (indirectMap != null) { json[r'indirect_map'] = indirectMap; - } return json; } /// Returns a new [MapTest] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static MapTest fromJson(dynamic value) { + static MapTest? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "MapTest[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "MapTest[$key]" has a null value in JSON.'); + }); + return true; + }()); + return MapTest( - mapMapOfString: mapCastOfType(json, r'map_map_of_string'), - mapOfEnumString: mapCastOfType(json, r'map_of_enum_string'), - directMap: mapCastOfType(json, r'direct_map'), - indirectMap: mapCastOfType(json, r'indirect_map'), + mapMapOfString: mapCastOfType(json, r'map_map_of_string') ?? const {}, + mapOfEnumString: mapCastOfType(json, r'map_of_enum_string') ?? const {}, + directMap: mapCastOfType(json, r'direct_map') ?? const {}, + indirectMap: mapCastOfType(json, r'indirect_map') ?? const {}, ); } return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(MapTest.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = MapTest.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = MapTest.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = MapTest.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of MapTest-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = MapTest.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = MapTest.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } @@ -120,7 +138,7 @@ class MapTestMapOfEnumStringEnum { final String value; @override - String toString() => value ?? ''; + String toString() => value; String toJson() => value; @@ -133,13 +151,20 @@ class MapTestMapOfEnumStringEnum { lower, ]; - static MapTestMapOfEnumStringEnum fromJson(dynamic value) => - MapTestMapOfEnumStringEnumTypeTransformer().decode(value); + static MapTestMapOfEnumStringEnum? fromJson(dynamic value) => MapTestMapOfEnumStringEnumTypeTransformer().decode(value); - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(MapTestMapOfEnumStringEnum.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = MapTestMapOfEnumStringEnum.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } } /// Transformation class that can [encode] an instance of [MapTestMapOfEnumStringEnum] to String, @@ -159,13 +184,13 @@ class MapTestMapOfEnumStringEnumTypeTransformer { /// /// The [allowNull] is very handy when an API changes and a new enum value is added or removed, /// and users are still using an old app with the old code. - MapTestMapOfEnumStringEnum decode(dynamic data, {bool allowNull}) { + MapTestMapOfEnumStringEnum? decode(dynamic data, {bool allowNull = true}) { if (data != null) { switch (data.toString()) { case r'UPPER': return MapTestMapOfEnumStringEnum.UPPER; case r'lower': return MapTestMapOfEnumStringEnum.lower; default: - if (allowNull == false) { + if (!allowNull) { throw ArgumentError('Unknown enum value to decode: $data'); } } @@ -174,7 +199,7 @@ class MapTestMapOfEnumStringEnumTypeTransformer { } /// Singleton [MapTestMapOfEnumStringEnumTypeTransformer] instance. - static MapTestMapOfEnumStringEnumTypeTransformer _instance; + static MapTestMapOfEnumStringEnumTypeTransformer? _instance; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/mixed_properties_and_additional_properties_class.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/mixed_properties_and_additional_properties_class.dart index 994be26f9e39..599c817a66ad 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/mixed_properties_and_additional_properties_class.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/mixed_properties_and_additional_properties_class.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -18,9 +18,21 @@ class MixedPropertiesAndAdditionalPropertiesClass { this.map = const {}, }); - String uuid; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? uuid; - DateTime dateTime; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + DateTime? dateTime; Map map; @@ -32,10 +44,10 @@ class MixedPropertiesAndAdditionalPropertiesClass { @override int get hashCode => - // ignore: unnecessary_parenthesis - (uuid == null ? 0 : uuid.hashCode) + - (dateTime == null ? 0 : dateTime.hashCode) + - (map == null ? 0 : map.hashCode); + // ignore: unnecessary_parenthesis + (uuid == null ? 0 : uuid!.hashCode) + + (dateTime == null ? 0 : dateTime!.hashCode) + + (map.hashCode); @override String toString() => 'MixedPropertiesAndAdditionalPropertiesClass[uuid=$uuid, dateTime=$dateTime, map=$map]'; @@ -46,59 +58,83 @@ class MixedPropertiesAndAdditionalPropertiesClass { json[r'uuid'] = uuid; } if (dateTime != null) { - json[r'dateTime'] = dateTime.toUtc().toIso8601String(); + json[r'dateTime'] = dateTime!.toUtc().toIso8601String(); } - if (map != null) { json[r'map'] = map; - } return json; } /// Returns a new [MixedPropertiesAndAdditionalPropertiesClass] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static MixedPropertiesAndAdditionalPropertiesClass fromJson(dynamic value) { + static MixedPropertiesAndAdditionalPropertiesClass? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "MixedPropertiesAndAdditionalPropertiesClass[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "MixedPropertiesAndAdditionalPropertiesClass[$key]" has a null value in JSON.'); + }); + return true; + }()); + return MixedPropertiesAndAdditionalPropertiesClass( uuid: mapValueOfType(json, r'uuid'), dateTime: mapDateTime(json, r'dateTime', ''), - map: mapValueOfType>(json, r'map'), + map: mapValueOfType>(json, r'map') ?? const {}, ); } return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(MixedPropertiesAndAdditionalPropertiesClass.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = MixedPropertiesAndAdditionalPropertiesClass.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = MixedPropertiesAndAdditionalPropertiesClass.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = MixedPropertiesAndAdditionalPropertiesClass.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of MixedPropertiesAndAdditionalPropertiesClass-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = MixedPropertiesAndAdditionalPropertiesClass.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = MixedPropertiesAndAdditionalPropertiesClass.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model200_response.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model200_response.dart index 01fbb8e4e9ae..de257edc7cc9 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model200_response.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model200_response.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -17,9 +17,21 @@ class Model200Response { this.class_, }); - int name; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? name; - String class_; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? class_; @override bool operator ==(Object other) => identical(this, other) || other is Model200Response && @@ -28,9 +40,9 @@ class Model200Response { @override int get hashCode => - // ignore: unnecessary_parenthesis - (name == null ? 0 : name.hashCode) + - (class_ == null ? 0 : class_.hashCode); + // ignore: unnecessary_parenthesis + (name == null ? 0 : name!.hashCode) + + (class_ == null ? 0 : class_!.hashCode); @override String toString() => 'Model200Response[name=$name, class_=$class_]'; @@ -49,9 +61,21 @@ class Model200Response { /// Returns a new [Model200Response] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static Model200Response fromJson(dynamic value) { + static Model200Response? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "Model200Response[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "Model200Response[$key]" has a null value in JSON.'); + }); + return true; + }()); + return Model200Response( name: mapValueOfType(json, r'name'), class_: mapValueOfType(json, r'class'), @@ -60,36 +84,50 @@ class Model200Response { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(Model200Response.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = Model200Response.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = Model200Response.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Model200Response.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of Model200Response-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = Model200Response.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Model200Response.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_client.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_client.dart index 9b3ef92da879..d48d030c9d06 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_client.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_client.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -16,7 +16,13 @@ class ModelClient { this.client, }); - String client; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? client; @override bool operator ==(Object other) => identical(this, other) || other is ModelClient && @@ -24,8 +30,8 @@ class ModelClient { @override int get hashCode => - // ignore: unnecessary_parenthesis - (client == null ? 0 : client.hashCode); + // ignore: unnecessary_parenthesis + (client == null ? 0 : client!.hashCode); @override String toString() => 'ModelClient[client=$client]'; @@ -41,9 +47,21 @@ class ModelClient { /// Returns a new [ModelClient] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static ModelClient fromJson(dynamic value) { + static ModelClient? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "ModelClient[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "ModelClient[$key]" has a null value in JSON.'); + }); + return true; + }()); + return ModelClient( client: mapValueOfType(json, r'client'), ); @@ -51,36 +69,50 @@ class ModelClient { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(ModelClient.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = ModelClient.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = ModelClient.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = ModelClient.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of ModelClient-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = ModelClient.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = ModelClient.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_file.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_file.dart index 66907de557c8..dc0f89b1c4f9 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_file.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_file.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -17,7 +17,13 @@ class ModelFile { }); /// Test capitalization - String sourceURI; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? sourceURI; @override bool operator ==(Object other) => identical(this, other) || other is ModelFile && @@ -25,8 +31,8 @@ class ModelFile { @override int get hashCode => - // ignore: unnecessary_parenthesis - (sourceURI == null ? 0 : sourceURI.hashCode); + // ignore: unnecessary_parenthesis + (sourceURI == null ? 0 : sourceURI!.hashCode); @override String toString() => 'ModelFile[sourceURI=$sourceURI]'; @@ -42,9 +48,21 @@ class ModelFile { /// Returns a new [ModelFile] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static ModelFile fromJson(dynamic value) { + static ModelFile? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "ModelFile[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "ModelFile[$key]" has a null value in JSON.'); + }); + return true; + }()); + return ModelFile( sourceURI: mapValueOfType(json, r'sourceURI'), ); @@ -52,36 +70,50 @@ class ModelFile { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(ModelFile.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = ModelFile.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = ModelFile.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = ModelFile.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of ModelFile-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = ModelFile.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = ModelFile.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_list.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_list.dart index e83b8055bc6f..d079e6aa221d 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_list.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_list.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -16,7 +16,13 @@ class ModelList { this.n123list, }); - String n123list; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? n123list; @override bool operator ==(Object other) => identical(this, other) || other is ModelList && @@ -24,8 +30,8 @@ class ModelList { @override int get hashCode => - // ignore: unnecessary_parenthesis - (n123list == null ? 0 : n123list.hashCode); + // ignore: unnecessary_parenthesis + (n123list == null ? 0 : n123list!.hashCode); @override String toString() => 'ModelList[n123list=$n123list]'; @@ -41,9 +47,21 @@ class ModelList { /// Returns a new [ModelList] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static ModelList fromJson(dynamic value) { + static ModelList? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "ModelList[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "ModelList[$key]" has a null value in JSON.'); + }); + return true; + }()); + return ModelList( n123list: mapValueOfType(json, r'123-list'), ); @@ -51,36 +69,50 @@ class ModelList { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(ModelList.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = ModelList.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = ModelList.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = ModelList.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of ModelList-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = ModelList.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = ModelList.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_return.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_return.dart index 3c740b8be854..3042ac8b3af5 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_return.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_return.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -16,7 +16,13 @@ class ModelReturn { this.return_, }); - int return_; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? return_; @override bool operator ==(Object other) => identical(this, other) || other is ModelReturn && @@ -24,8 +30,8 @@ class ModelReturn { @override int get hashCode => - // ignore: unnecessary_parenthesis - (return_ == null ? 0 : return_.hashCode); + // ignore: unnecessary_parenthesis + (return_ == null ? 0 : return_!.hashCode); @override String toString() => 'ModelReturn[return_=$return_]'; @@ -41,9 +47,21 @@ class ModelReturn { /// Returns a new [ModelReturn] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static ModelReturn fromJson(dynamic value) { + static ModelReturn? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "ModelReturn[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "ModelReturn[$key]" has a null value in JSON.'); + }); + return true; + }()); + return ModelReturn( return_: mapValueOfType(json, r'return'), ); @@ -51,36 +69,50 @@ class ModelReturn { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(ModelReturn.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = ModelReturn.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = ModelReturn.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = ModelReturn.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of ModelReturn-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = ModelReturn.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = ModelReturn.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/name.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/name.dart index d0c3106e3266..10461ccba2b6 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/name.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/name.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -13,7 +13,7 @@ part of openapi.api; class Name { /// Returns a new [Name] instance. Name({ - @required this.name, + required this.name, this.snakeCase, this.property, this.n123number, @@ -21,11 +21,29 @@ class Name { int name; - int snakeCase; - - String property; - - int n123number; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? snakeCase; + + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? property; + + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? n123number; @override bool operator ==(Object other) => identical(this, other) || other is Name && @@ -36,11 +54,11 @@ class Name { @override int get hashCode => - // ignore: unnecessary_parenthesis - (name == null ? 0 : name.hashCode) + - (snakeCase == null ? 0 : snakeCase.hashCode) + - (property == null ? 0 : property.hashCode) + - (n123number == null ? 0 : n123number.hashCode); + // ignore: unnecessary_parenthesis + (name.hashCode) + + (snakeCase == null ? 0 : snakeCase!.hashCode) + + (property == null ? 0 : property!.hashCode) + + (n123number == null ? 0 : n123number!.hashCode); @override String toString() => 'Name[name=$name, snakeCase=$snakeCase, property=$property, n123number=$n123number]'; @@ -63,11 +81,23 @@ class Name { /// Returns a new [Name] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static Name fromJson(dynamic value) { + static Name? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "Name[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "Name[$key]" has a null value in JSON.'); + }); + return true; + }()); + return Name( - name: mapValueOfType(json, r'name'), + name: mapValueOfType(json, r'name')!, snakeCase: mapValueOfType(json, r'snake_case'), property: mapValueOfType(json, r'property'), n123number: mapValueOfType(json, r'123Number'), @@ -76,36 +106,51 @@ class Name { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(Name.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = Name.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = Name.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Name.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of Name-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = Name.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Name.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + 'name', + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/nullable_class.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/nullable_class.dart index 469db464a5f9..2f3d55046fed 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/nullable_class.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/nullable_class.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -19,35 +19,35 @@ class NullableClass { this.stringProp, this.dateProp, this.datetimeProp, - this.arrayNullableProp, - this.arrayAndItemsNullableProp, + this.arrayNullableProp = const [], + this.arrayAndItemsNullableProp = const [], this.arrayItemsNullable = const [], - this.objectNullableProp, - this.objectAndItemsNullableProp, + this.objectNullableProp = const {}, + this.objectAndItemsNullableProp = const {}, this.objectItemsNullable = const {}, }); - int integerProp; + int? integerProp; - num numberProp; + num? numberProp; - bool booleanProp; + bool? booleanProp; - String stringProp; + String? stringProp; - DateTime dateProp; + DateTime? dateProp; - DateTime datetimeProp; + DateTime? datetimeProp; - List arrayNullableProp; + List? arrayNullableProp; - List arrayAndItemsNullableProp; + List? arrayAndItemsNullableProp; List arrayItemsNullable; - Map objectNullableProp; + Map? objectNullableProp; - Map objectAndItemsNullableProp; + Map? objectAndItemsNullableProp; Map objectItemsNullable; @@ -68,19 +68,19 @@ class NullableClass { @override int get hashCode => - // ignore: unnecessary_parenthesis - (integerProp == null ? 0 : integerProp.hashCode) + - (numberProp == null ? 0 : numberProp.hashCode) + - (booleanProp == null ? 0 : booleanProp.hashCode) + - (stringProp == null ? 0 : stringProp.hashCode) + - (dateProp == null ? 0 : dateProp.hashCode) + - (datetimeProp == null ? 0 : datetimeProp.hashCode) + - (arrayNullableProp == null ? 0 : arrayNullableProp.hashCode) + - (arrayAndItemsNullableProp == null ? 0 : arrayAndItemsNullableProp.hashCode) + - (arrayItemsNullable == null ? 0 : arrayItemsNullable.hashCode) + - (objectNullableProp == null ? 0 : objectNullableProp.hashCode) + - (objectAndItemsNullableProp == null ? 0 : objectAndItemsNullableProp.hashCode) + - (objectItemsNullable == null ? 0 : objectItemsNullable.hashCode); + // ignore: unnecessary_parenthesis + (integerProp == null ? 0 : integerProp!.hashCode) + + (numberProp == null ? 0 : numberProp!.hashCode) + + (booleanProp == null ? 0 : booleanProp!.hashCode) + + (stringProp == null ? 0 : stringProp!.hashCode) + + (dateProp == null ? 0 : dateProp!.hashCode) + + (datetimeProp == null ? 0 : datetimeProp!.hashCode) + + (arrayNullableProp == null ? 0 : arrayNullableProp!.hashCode) + + (arrayAndItemsNullableProp == null ? 0 : arrayAndItemsNullableProp!.hashCode) + + (arrayItemsNullable.hashCode) + + (objectNullableProp == null ? 0 : objectNullableProp!.hashCode) + + (objectAndItemsNullableProp == null ? 0 : objectAndItemsNullableProp!.hashCode) + + (objectItemsNullable.hashCode); @override String toString() => 'NullableClass[integerProp=$integerProp, numberProp=$numberProp, booleanProp=$booleanProp, stringProp=$stringProp, dateProp=$dateProp, datetimeProp=$datetimeProp, arrayNullableProp=$arrayNullableProp, arrayAndItemsNullableProp=$arrayAndItemsNullableProp, arrayItemsNullable=$arrayItemsNullable, objectNullableProp=$objectNullableProp, objectAndItemsNullableProp=$objectAndItemsNullableProp, objectItemsNullable=$objectItemsNullable]'; @@ -100,10 +100,10 @@ class NullableClass { json[r'string_prop'] = stringProp; } if (dateProp != null) { - json[r'date_prop'] = _dateFormatter.format(dateProp.toUtc()); + json[r'date_prop'] = _dateFormatter.format(dateProp!.toUtc()); } if (datetimeProp != null) { - json[r'datetime_prop'] = datetimeProp.toUtc().toIso8601String(); + json[r'datetime_prop'] = datetimeProp!.toUtc().toIso8601String(); } if (arrayNullableProp != null) { json[r'array_nullable_prop'] = arrayNullableProp; @@ -111,77 +111,99 @@ class NullableClass { if (arrayAndItemsNullableProp != null) { json[r'array_and_items_nullable_prop'] = arrayAndItemsNullableProp; } - if (arrayItemsNullable != null) { json[r'array_items_nullable'] = arrayItemsNullable; - } if (objectNullableProp != null) { json[r'object_nullable_prop'] = objectNullableProp; } if (objectAndItemsNullableProp != null) { json[r'object_and_items_nullable_prop'] = objectAndItemsNullableProp; } - if (objectItemsNullable != null) { json[r'object_items_nullable'] = objectItemsNullable; - } return json; } /// Returns a new [NullableClass] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static NullableClass fromJson(dynamic value) { + static NullableClass? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "NullableClass[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "NullableClass[$key]" has a null value in JSON.'); + }); + return true; + }()); + return NullableClass( integerProp: mapValueOfType(json, r'integer_prop'), numberProp: json[r'number_prop'] == null - ? null - : num.parse(json[r'number_prop'].toString()), + ? null + : num.parse(json[r'number_prop'].toString()), booleanProp: mapValueOfType(json, r'boolean_prop'), stringProp: mapValueOfType(json, r'string_prop'), dateProp: mapDateTime(json, r'date_prop', ''), datetimeProp: mapDateTime(json, r'datetime_prop', ''), - arrayNullableProp: Object.listFromJson(json[r'array_nullable_prop']), - arrayAndItemsNullableProp: Object.listFromJson(json[r'array_and_items_nullable_prop']), - arrayItemsNullable: Object.listFromJson(json[r'array_items_nullable']), - objectNullableProp: mapValueOfType>(json, r'object_nullable_prop'), - objectAndItemsNullableProp: mapValueOfType>(json, r'object_and_items_nullable_prop'), - objectItemsNullable: mapValueOfType>(json, r'object_items_nullable'), + arrayNullableProp: Object.listFromJson(json[r'array_nullable_prop']) ?? const [], + arrayAndItemsNullableProp: Object.listFromJson(json[r'array_and_items_nullable_prop']) ?? const [], + arrayItemsNullable: Object.listFromJson(json[r'array_items_nullable']) ?? const [], + objectNullableProp: mapValueOfType>(json, r'object_nullable_prop') ?? const {}, + objectAndItemsNullableProp: mapValueOfType>(json, r'object_and_items_nullable_prop') ?? const {}, + objectItemsNullable: mapValueOfType>(json, r'object_items_nullable') ?? const {}, ); } return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(NullableClass.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = NullableClass.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = NullableClass.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = NullableClass.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of NullableClass-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = NullableClass.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = NullableClass.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/number_only.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/number_only.dart index 686cfff791f8..2a927dc41d6a 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/number_only.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/number_only.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -16,7 +16,13 @@ class NumberOnly { this.justNumber, }); - num justNumber; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + num? justNumber; @override bool operator ==(Object other) => identical(this, other) || other is NumberOnly && @@ -24,8 +30,8 @@ class NumberOnly { @override int get hashCode => - // ignore: unnecessary_parenthesis - (justNumber == null ? 0 : justNumber.hashCode); + // ignore: unnecessary_parenthesis + (justNumber == null ? 0 : justNumber!.hashCode); @override String toString() => 'NumberOnly[justNumber=$justNumber]'; @@ -41,48 +47,74 @@ class NumberOnly { /// Returns a new [NumberOnly] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static NumberOnly fromJson(dynamic value) { + static NumberOnly? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "NumberOnly[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "NumberOnly[$key]" has a null value in JSON.'); + }); + return true; + }()); + return NumberOnly( justNumber: json[r'JustNumber'] == null - ? null - : num.parse(json[r'JustNumber'].toString()), + ? null + : num.parse(json[r'JustNumber'].toString()), ); } return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(NumberOnly.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = NumberOnly.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = NumberOnly.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = NumberOnly.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of NumberOnly-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = NumberOnly.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = NumberOnly.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/object_with_deprecated_fields.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/object_with_deprecated_fields.dart index b5e83009cf92..924aaeaafae4 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/object_with_deprecated_fields.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/object_with_deprecated_fields.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -19,11 +19,29 @@ class ObjectWithDeprecatedFields { this.bars = const [], }); - String uuid; - - num id; - - DeprecatedObject deprecatedRef; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? uuid; + + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + num? id; + + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + DeprecatedObject? deprecatedRef; List bars; @@ -36,11 +54,11 @@ class ObjectWithDeprecatedFields { @override int get hashCode => - // ignore: unnecessary_parenthesis - (uuid == null ? 0 : uuid.hashCode) + - (id == null ? 0 : id.hashCode) + - (deprecatedRef == null ? 0 : deprecatedRef.hashCode) + - (bars == null ? 0 : bars.hashCode); + // ignore: unnecessary_parenthesis + (uuid == null ? 0 : uuid!.hashCode) + + (id == null ? 0 : id!.hashCode) + + (deprecatedRef == null ? 0 : deprecatedRef!.hashCode) + + (bars.hashCode); @override String toString() => 'ObjectWithDeprecatedFields[uuid=$uuid, id=$id, deprecatedRef=$deprecatedRef, bars=$bars]'; @@ -56,62 +74,86 @@ class ObjectWithDeprecatedFields { if (deprecatedRef != null) { json[r'deprecatedRef'] = deprecatedRef; } - if (bars != null) { json[r'bars'] = bars; - } return json; } /// Returns a new [ObjectWithDeprecatedFields] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static ObjectWithDeprecatedFields fromJson(dynamic value) { + static ObjectWithDeprecatedFields? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "ObjectWithDeprecatedFields[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "ObjectWithDeprecatedFields[$key]" has a null value in JSON.'); + }); + return true; + }()); + return ObjectWithDeprecatedFields( uuid: mapValueOfType(json, r'uuid'), id: json[r'id'] == null - ? null - : num.parse(json[r'id'].toString()), + ? null + : num.parse(json[r'id'].toString()), deprecatedRef: DeprecatedObject.fromJson(json[r'deprecatedRef']), bars: json[r'bars'] is List - ? (json[r'bars'] as List).cast() - : null, + ? (json[r'bars'] as List).cast() + : const [], ); } return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(ObjectWithDeprecatedFields.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = ObjectWithDeprecatedFields.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = ObjectWithDeprecatedFields.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = ObjectWithDeprecatedFields.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of ObjectWithDeprecatedFields-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = ObjectWithDeprecatedFields.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = ObjectWithDeprecatedFields.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/order.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/order.dart index 61d01acfaaa8..ad84a894e8db 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/order.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/order.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -21,16 +21,40 @@ class Order { this.complete = false, }); - int id; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? id; - int petId; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? petId; - int quantity; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? quantity; - DateTime shipDate; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + DateTime? shipDate; /// Order Status - OrderStatusEnum status; + OrderStatusEnum? status; bool complete; @@ -45,13 +69,13 @@ class Order { @override int get hashCode => - // ignore: unnecessary_parenthesis - (id == null ? 0 : id.hashCode) + - (petId == null ? 0 : petId.hashCode) + - (quantity == null ? 0 : quantity.hashCode) + - (shipDate == null ? 0 : shipDate.hashCode) + - (status == null ? 0 : status.hashCode) + - (complete == null ? 0 : complete.hashCode); + // ignore: unnecessary_parenthesis + (id == null ? 0 : id!.hashCode) + + (petId == null ? 0 : petId!.hashCode) + + (quantity == null ? 0 : quantity!.hashCode) + + (shipDate == null ? 0 : shipDate!.hashCode) + + (status == null ? 0 : status!.hashCode) + + (complete.hashCode); @override String toString() => 'Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete]'; @@ -68,66 +92,90 @@ class Order { json[r'quantity'] = quantity; } if (shipDate != null) { - json[r'shipDate'] = shipDate.toUtc().toIso8601String(); + json[r'shipDate'] = shipDate!.toUtc().toIso8601String(); } if (status != null) { json[r'status'] = status; } - if (complete != null) { json[r'complete'] = complete; - } return json; } /// Returns a new [Order] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static Order fromJson(dynamic value) { + static Order? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "Order[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "Order[$key]" has a null value in JSON.'); + }); + return true; + }()); + return Order( id: mapValueOfType(json, r'id'), petId: mapValueOfType(json, r'petId'), quantity: mapValueOfType(json, r'quantity'), shipDate: mapDateTime(json, r'shipDate', ''), status: OrderStatusEnum.fromJson(json[r'status']), - complete: mapValueOfType(json, r'complete'), + complete: mapValueOfType(json, r'complete') ?? false, ); } return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(Order.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = Order.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = Order.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Order.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of Order-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = Order.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Order.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } /// Order Status @@ -139,7 +187,7 @@ class OrderStatusEnum { final String value; @override - String toString() => value ?? ''; + String toString() => value; String toJson() => value; @@ -154,13 +202,20 @@ class OrderStatusEnum { delivered, ]; - static OrderStatusEnum fromJson(dynamic value) => - OrderStatusEnumTypeTransformer().decode(value); + static OrderStatusEnum? fromJson(dynamic value) => OrderStatusEnumTypeTransformer().decode(value); - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(OrderStatusEnum.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = OrderStatusEnum.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } } /// Transformation class that can [encode] an instance of [OrderStatusEnum] to String, @@ -180,14 +235,14 @@ class OrderStatusEnumTypeTransformer { /// /// The [allowNull] is very handy when an API changes and a new enum value is added or removed, /// and users are still using an old app with the old code. - OrderStatusEnum decode(dynamic data, {bool allowNull}) { + OrderStatusEnum? decode(dynamic data, {bool allowNull = true}) { if (data != null) { switch (data.toString()) { case r'placed': return OrderStatusEnum.placed; case r'approved': return OrderStatusEnum.approved; case r'delivered': return OrderStatusEnum.delivered; default: - if (allowNull == false) { + if (!allowNull) { throw ArgumentError('Unknown enum value to decode: $data'); } } @@ -196,7 +251,7 @@ class OrderStatusEnumTypeTransformer { } /// Singleton [OrderStatusEnumTypeTransformer] instance. - static OrderStatusEnumTypeTransformer _instance; + static OrderStatusEnumTypeTransformer? _instance; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_composite.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_composite.dart index 6ea8ef2ad983..c60b3d287a12 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_composite.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_composite.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -18,11 +18,29 @@ class OuterComposite { this.myBoolean, }); - num myNumber; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + num? myNumber; - String myString; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? myString; - bool myBoolean; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + bool? myBoolean; @override bool operator ==(Object other) => identical(this, other) || other is OuterComposite && @@ -32,10 +50,10 @@ class OuterComposite { @override int get hashCode => - // ignore: unnecessary_parenthesis - (myNumber == null ? 0 : myNumber.hashCode) + - (myString == null ? 0 : myString.hashCode) + - (myBoolean == null ? 0 : myBoolean.hashCode); + // ignore: unnecessary_parenthesis + (myNumber == null ? 0 : myNumber!.hashCode) + + (myString == null ? 0 : myString!.hashCode) + + (myBoolean == null ? 0 : myBoolean!.hashCode); @override String toString() => 'OuterComposite[myNumber=$myNumber, myString=$myString, myBoolean=$myBoolean]'; @@ -57,13 +75,25 @@ class OuterComposite { /// Returns a new [OuterComposite] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static OuterComposite fromJson(dynamic value) { + static OuterComposite? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "OuterComposite[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "OuterComposite[$key]" has a null value in JSON.'); + }); + return true; + }()); + return OuterComposite( myNumber: json[r'my_number'] == null - ? null - : num.parse(json[r'my_number'].toString()), + ? null + : num.parse(json[r'my_number'].toString()), myString: mapValueOfType(json, r'my_string'), myBoolean: mapValueOfType(json, r'my_boolean'), ); @@ -71,36 +101,50 @@ class OuterComposite { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(OuterComposite.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = OuterComposite.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = OuterComposite.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = OuterComposite.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of OuterComposite-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = OuterComposite.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = OuterComposite.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum.dart index 13e54eb7e599..79990cc426ae 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -19,7 +19,7 @@ class OuterEnum { final String value; @override - String toString() => value ?? ''; + String toString() => value; String toJson() => value; @@ -34,13 +34,20 @@ class OuterEnum { delivered, ]; - static OuterEnum fromJson(dynamic value) => - OuterEnumTypeTransformer().decode(value); + static OuterEnum? fromJson(dynamic value) => OuterEnumTypeTransformer().decode(value); - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(OuterEnum.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = OuterEnum.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } } /// Transformation class that can [encode] an instance of [OuterEnum] to String, @@ -60,14 +67,14 @@ class OuterEnumTypeTransformer { /// /// The [allowNull] is very handy when an API changes and a new enum value is added or removed, /// and users are still using an old app with the old code. - OuterEnum decode(dynamic data, {bool allowNull}) { + OuterEnum? decode(dynamic data, {bool allowNull = true}) { if (data != null) { switch (data.toString()) { case r'placed': return OuterEnum.placed; case r'approved': return OuterEnum.approved; case r'delivered': return OuterEnum.delivered; default: - if (allowNull == false) { + if (!allowNull) { throw ArgumentError('Unknown enum value to decode: $data'); } } @@ -76,6 +83,6 @@ class OuterEnumTypeTransformer { } /// Singleton [OuterEnumTypeTransformer] instance. - static OuterEnumTypeTransformer _instance; + static OuterEnumTypeTransformer? _instance; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum_default_value.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum_default_value.dart index 5b2b1d500e51..710bffc01d65 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum_default_value.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum_default_value.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -19,7 +19,7 @@ class OuterEnumDefaultValue { final String value; @override - String toString() => value ?? ''; + String toString() => value; String toJson() => value; @@ -34,13 +34,20 @@ class OuterEnumDefaultValue { delivered, ]; - static OuterEnumDefaultValue fromJson(dynamic value) => - OuterEnumDefaultValueTypeTransformer().decode(value); + static OuterEnumDefaultValue? fromJson(dynamic value) => OuterEnumDefaultValueTypeTransformer().decode(value); - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(OuterEnumDefaultValue.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = OuterEnumDefaultValue.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } } /// Transformation class that can [encode] an instance of [OuterEnumDefaultValue] to String, @@ -60,14 +67,14 @@ class OuterEnumDefaultValueTypeTransformer { /// /// The [allowNull] is very handy when an API changes and a new enum value is added or removed, /// and users are still using an old app with the old code. - OuterEnumDefaultValue decode(dynamic data, {bool allowNull}) { + OuterEnumDefaultValue? decode(dynamic data, {bool allowNull = true}) { if (data != null) { switch (data.toString()) { case r'placed': return OuterEnumDefaultValue.placed; case r'approved': return OuterEnumDefaultValue.approved; case r'delivered': return OuterEnumDefaultValue.delivered; default: - if (allowNull == false) { + if (!allowNull) { throw ArgumentError('Unknown enum value to decode: $data'); } } @@ -76,6 +83,6 @@ class OuterEnumDefaultValueTypeTransformer { } /// Singleton [OuterEnumDefaultValueTypeTransformer] instance. - static OuterEnumDefaultValueTypeTransformer _instance; + static OuterEnumDefaultValueTypeTransformer? _instance; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum_integer.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum_integer.dart index 6becb11fd9ae..7d0f2e371b11 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum_integer.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum_integer.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -19,7 +19,7 @@ class OuterEnumInteger { final int value; @override - String toString() => value == null ? '' : value.toString(); + String toString() => value.toString(); int toJson() => value; @@ -34,13 +34,20 @@ class OuterEnumInteger { number2, ]; - static OuterEnumInteger fromJson(dynamic value) => - OuterEnumIntegerTypeTransformer().decode(value); + static OuterEnumInteger? fromJson(dynamic value) => OuterEnumIntegerTypeTransformer().decode(value); - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(OuterEnumInteger.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = OuterEnumInteger.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } } /// Transformation class that can [encode] an instance of [OuterEnumInteger] to int, @@ -60,14 +67,14 @@ class OuterEnumIntegerTypeTransformer { /// /// The [allowNull] is very handy when an API changes and a new enum value is added or removed, /// and users are still using an old app with the old code. - OuterEnumInteger decode(dynamic data, {bool allowNull}) { + OuterEnumInteger? decode(dynamic data, {bool allowNull = true}) { if (data != null) { switch (data.toString()) { case 0: return OuterEnumInteger.number0; case 1: return OuterEnumInteger.number1; case 2: return OuterEnumInteger.number2; default: - if (allowNull == false) { + if (!allowNull) { throw ArgumentError('Unknown enum value to decode: $data'); } } @@ -76,6 +83,6 @@ class OuterEnumIntegerTypeTransformer { } /// Singleton [OuterEnumIntegerTypeTransformer] instance. - static OuterEnumIntegerTypeTransformer _instance; + static OuterEnumIntegerTypeTransformer? _instance; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum_integer_default_value.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum_integer_default_value.dart index 5e534ea0f5c4..f82ae23497b3 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum_integer_default_value.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum_integer_default_value.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -19,7 +19,7 @@ class OuterEnumIntegerDefaultValue { final int value; @override - String toString() => value == null ? '' : value.toString(); + String toString() => value.toString(); int toJson() => value; @@ -34,13 +34,20 @@ class OuterEnumIntegerDefaultValue { number2, ]; - static OuterEnumIntegerDefaultValue fromJson(dynamic value) => - OuterEnumIntegerDefaultValueTypeTransformer().decode(value); + static OuterEnumIntegerDefaultValue? fromJson(dynamic value) => OuterEnumIntegerDefaultValueTypeTransformer().decode(value); - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(OuterEnumIntegerDefaultValue.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = OuterEnumIntegerDefaultValue.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } } /// Transformation class that can [encode] an instance of [OuterEnumIntegerDefaultValue] to int, @@ -60,14 +67,14 @@ class OuterEnumIntegerDefaultValueTypeTransformer { /// /// The [allowNull] is very handy when an API changes and a new enum value is added or removed, /// and users are still using an old app with the old code. - OuterEnumIntegerDefaultValue decode(dynamic data, {bool allowNull}) { + OuterEnumIntegerDefaultValue? decode(dynamic data, {bool allowNull = true}) { if (data != null) { switch (data.toString()) { case 0: return OuterEnumIntegerDefaultValue.number0; case 1: return OuterEnumIntegerDefaultValue.number1; case 2: return OuterEnumIntegerDefaultValue.number2; default: - if (allowNull == false) { + if (!allowNull) { throw ArgumentError('Unknown enum value to decode: $data'); } } @@ -76,6 +83,6 @@ class OuterEnumIntegerDefaultValueTypeTransformer { } /// Singleton [OuterEnumIntegerDefaultValueTypeTransformer] instance. - static OuterEnumIntegerDefaultValueTypeTransformer _instance; + static OuterEnumIntegerDefaultValueTypeTransformer? _instance; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_object_with_enum_property.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_object_with_enum_property.dart index 3ca207b7b742..8b9b76380e6d 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_object_with_enum_property.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_object_with_enum_property.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -13,7 +13,7 @@ part of openapi.api; class OuterObjectWithEnumProperty { /// Returns a new [OuterObjectWithEnumProperty] instance. OuterObjectWithEnumProperty({ - @required this.value, + required this.value, }); OuterEnumInteger value; @@ -24,8 +24,8 @@ class OuterObjectWithEnumProperty { @override int get hashCode => - // ignore: unnecessary_parenthesis - (value == null ? 0 : value.hashCode); + // ignore: unnecessary_parenthesis + (value.hashCode); @override String toString() => 'OuterObjectWithEnumProperty[value=$value]'; @@ -39,46 +39,73 @@ class OuterObjectWithEnumProperty { /// Returns a new [OuterObjectWithEnumProperty] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static OuterObjectWithEnumProperty fromJson(dynamic value) { + static OuterObjectWithEnumProperty? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "OuterObjectWithEnumProperty[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "OuterObjectWithEnumProperty[$key]" has a null value in JSON.'); + }); + return true; + }()); + return OuterObjectWithEnumProperty( - value: OuterEnumInteger.fromJson(json[r'value']), + value: OuterEnumInteger.fromJson(json[r'value'])!, ); } return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(OuterObjectWithEnumProperty.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = OuterObjectWithEnumProperty.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = OuterObjectWithEnumProperty.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = OuterObjectWithEnumProperty.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of OuterObjectWithEnumProperty-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = OuterObjectWithEnumProperty.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = OuterObjectWithEnumProperty.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + 'value', + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/pet.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/pet.dart index 988948fe7c77..e9a89d7b51b9 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/pet.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/pet.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -15,15 +15,27 @@ class Pet { Pet({ this.id, this.category, - @required this.name, + required this.name, this.photoUrls = const {}, this.tags = const [], this.status, }); - int id; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? id; - Category category; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + Category? category; String name; @@ -32,7 +44,7 @@ class Pet { List tags; /// pet status in the store - PetStatusEnum status; + PetStatusEnum? status; @override bool operator ==(Object other) => identical(this, other) || other is Pet && @@ -45,13 +57,13 @@ class Pet { @override int get hashCode => - // ignore: unnecessary_parenthesis - (id == null ? 0 : id.hashCode) + - (category == null ? 0 : category.hashCode) + - (name == null ? 0 : name.hashCode) + - (photoUrls == null ? 0 : photoUrls.hashCode) + - (tags == null ? 0 : tags.hashCode) + - (status == null ? 0 : status.hashCode); + // ignore: unnecessary_parenthesis + (id == null ? 0 : id!.hashCode) + + (category == null ? 0 : category!.hashCode) + + (name.hashCode) + + (photoUrls.hashCode) + + (tags.hashCode) + + (status == null ? 0 : status!.hashCode); @override String toString() => 'Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$status]'; @@ -66,9 +78,7 @@ class Pet { } json[r'name'] = name; json[r'photoUrls'] = photoUrls; - if (tags != null) { json[r'tags'] = tags; - } if (status != null) { json[r'status'] = status; } @@ -78,54 +88,82 @@ class Pet { /// Returns a new [Pet] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static Pet fromJson(dynamic value) { + static Pet? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "Pet[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "Pet[$key]" has a null value in JSON.'); + }); + return true; + }()); + return Pet( id: mapValueOfType(json, r'id'), category: Category.fromJson(json[r'category']), - name: mapValueOfType(json, r'name'), + name: mapValueOfType(json, r'name')!, photoUrls: json[r'photoUrls'] is Set - ? (json[r'photoUrls'] as Set).cast() - : null, - tags: Tag.listFromJson(json[r'tags']), + ? (json[r'photoUrls'] as Set).cast() + : const {}, + tags: Tag.listFromJson(json[r'tags']) ?? const [], status: PetStatusEnum.fromJson(json[r'status']), ); } return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(Pet.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = Pet.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = Pet.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Pet.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of Pet-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = Pet.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Pet.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + 'name', + 'photoUrls', + }; } /// pet status in the store @@ -137,7 +175,7 @@ class PetStatusEnum { final String value; @override - String toString() => value ?? ''; + String toString() => value; String toJson() => value; @@ -152,13 +190,20 @@ class PetStatusEnum { sold, ]; - static PetStatusEnum fromJson(dynamic value) => - PetStatusEnumTypeTransformer().decode(value); + static PetStatusEnum? fromJson(dynamic value) => PetStatusEnumTypeTransformer().decode(value); - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(PetStatusEnum.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = PetStatusEnum.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } } /// Transformation class that can [encode] an instance of [PetStatusEnum] to String, @@ -178,14 +223,14 @@ class PetStatusEnumTypeTransformer { /// /// The [allowNull] is very handy when an API changes and a new enum value is added or removed, /// and users are still using an old app with the old code. - PetStatusEnum decode(dynamic data, {bool allowNull}) { + PetStatusEnum? decode(dynamic data, {bool allowNull = true}) { if (data != null) { switch (data.toString()) { case r'available': return PetStatusEnum.available; case r'pending': return PetStatusEnum.pending; case r'sold': return PetStatusEnum.sold; default: - if (allowNull == false) { + if (!allowNull) { throw ArgumentError('Unknown enum value to decode: $data'); } } @@ -194,7 +239,7 @@ class PetStatusEnumTypeTransformer { } /// Singleton [PetStatusEnumTypeTransformer] instance. - static PetStatusEnumTypeTransformer _instance; + static PetStatusEnumTypeTransformer? _instance; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/read_only_first.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/read_only_first.dart index b1a1fe0c1d0f..6cda0773d11d 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/read_only_first.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/read_only_first.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -17,9 +17,21 @@ class ReadOnlyFirst { this.baz, }); - String bar; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? bar; - String baz; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? baz; @override bool operator ==(Object other) => identical(this, other) || other is ReadOnlyFirst && @@ -28,9 +40,9 @@ class ReadOnlyFirst { @override int get hashCode => - // ignore: unnecessary_parenthesis - (bar == null ? 0 : bar.hashCode) + - (baz == null ? 0 : baz.hashCode); + // ignore: unnecessary_parenthesis + (bar == null ? 0 : bar!.hashCode) + + (baz == null ? 0 : baz!.hashCode); @override String toString() => 'ReadOnlyFirst[bar=$bar, baz=$baz]'; @@ -49,9 +61,21 @@ class ReadOnlyFirst { /// Returns a new [ReadOnlyFirst] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static ReadOnlyFirst fromJson(dynamic value) { + static ReadOnlyFirst? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "ReadOnlyFirst[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "ReadOnlyFirst[$key]" has a null value in JSON.'); + }); + return true; + }()); + return ReadOnlyFirst( bar: mapValueOfType(json, r'bar'), baz: mapValueOfType(json, r'baz'), @@ -60,36 +84,50 @@ class ReadOnlyFirst { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(ReadOnlyFirst.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = ReadOnlyFirst.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = ReadOnlyFirst.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = ReadOnlyFirst.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of ReadOnlyFirst-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = ReadOnlyFirst.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = ReadOnlyFirst.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/special_model_name.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/special_model_name.dart index 5ed9408d26a2..bdfecbd2e7de 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/special_model_name.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/special_model_name.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -16,7 +16,13 @@ class SpecialModelName { this.dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket, }); - int dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket; @override bool operator ==(Object other) => identical(this, other) || other is SpecialModelName && @@ -24,8 +30,8 @@ class SpecialModelName { @override int get hashCode => - // ignore: unnecessary_parenthesis - (dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket == null ? 0 : dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket.hashCode); + // ignore: unnecessary_parenthesis + (dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket == null ? 0 : dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket!.hashCode); @override String toString() => 'SpecialModelName[dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket=$dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket]'; @@ -41,9 +47,21 @@ class SpecialModelName { /// Returns a new [SpecialModelName] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static SpecialModelName fromJson(dynamic value) { + static SpecialModelName? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "SpecialModelName[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "SpecialModelName[$key]" has a null value in JSON.'); + }); + return true; + }()); + return SpecialModelName( dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket: mapValueOfType(json, r'$special[property.name]'), ); @@ -51,36 +69,50 @@ class SpecialModelName { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(SpecialModelName.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = SpecialModelName.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = SpecialModelName.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = SpecialModelName.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of SpecialModelName-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = SpecialModelName.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = SpecialModelName.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/tag.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/tag.dart index 193c7004028f..71b8799d1cb1 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/tag.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/tag.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -17,9 +17,21 @@ class Tag { this.name, }); - int id; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? id; - String name; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? name; @override bool operator ==(Object other) => identical(this, other) || other is Tag && @@ -28,9 +40,9 @@ class Tag { @override int get hashCode => - // ignore: unnecessary_parenthesis - (id == null ? 0 : id.hashCode) + - (name == null ? 0 : name.hashCode); + // ignore: unnecessary_parenthesis + (id == null ? 0 : id!.hashCode) + + (name == null ? 0 : name!.hashCode); @override String toString() => 'Tag[id=$id, name=$name]'; @@ -49,9 +61,21 @@ class Tag { /// Returns a new [Tag] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static Tag fromJson(dynamic value) { + static Tag? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "Tag[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "Tag[$key]" has a null value in JSON.'); + }); + return true; + }()); + return Tag( id: mapValueOfType(json, r'id'), name: mapValueOfType(json, r'name'), @@ -60,36 +84,50 @@ class Tag { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(Tag.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = Tag.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = Tag.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Tag.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of Tag-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = Tag.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = Tag.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/user.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/user.dart index d2b94ed6a7ab..0b10d4fe7c23 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/user.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/user.dart @@ -1,7 +1,7 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first @@ -23,22 +23,70 @@ class User { this.userStatus, }); - int id; - - String username; - - String firstName; - - String lastName; - - String email; - - String password; - - String phone; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? id; + + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? username; + + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? firstName; + + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? lastName; + + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? email; + + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? password; + + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + String? phone; /// User Status - int userStatus; + /// + /// Please note: This property should have been non-nullable! Since the specification file + /// does not include a default value (using the "default:" property), however, the generated + /// source code must fall back to having a nullable type. + /// Consider adding a "default:" property in the specification file to hide this note. + /// + int? userStatus; @override bool operator ==(Object other) => identical(this, other) || other is User && @@ -53,15 +101,15 @@ class User { @override int get hashCode => - // ignore: unnecessary_parenthesis - (id == null ? 0 : id.hashCode) + - (username == null ? 0 : username.hashCode) + - (firstName == null ? 0 : firstName.hashCode) + - (lastName == null ? 0 : lastName.hashCode) + - (email == null ? 0 : email.hashCode) + - (password == null ? 0 : password.hashCode) + - (phone == null ? 0 : phone.hashCode) + - (userStatus == null ? 0 : userStatus.hashCode); + // ignore: unnecessary_parenthesis + (id == null ? 0 : id!.hashCode) + + (username == null ? 0 : username!.hashCode) + + (firstName == null ? 0 : firstName!.hashCode) + + (lastName == null ? 0 : lastName!.hashCode) + + (email == null ? 0 : email!.hashCode) + + (password == null ? 0 : password!.hashCode) + + (phone == null ? 0 : phone!.hashCode) + + (userStatus == null ? 0 : userStatus!.hashCode); @override String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]'; @@ -98,9 +146,21 @@ class User { /// Returns a new [User] instance and imports its values from /// [value] if it's a [Map], null otherwise. // ignore: prefer_constructors_over_static_methods - static User fromJson(dynamic value) { + static User? fromJson(dynamic value) { if (value is Map) { final json = value.cast(); + + // Ensure that the map contains the required keys. + // Note 1: the values aren't checked for validity beyond being non-null. + // Note 2: this code is stripped in release mode! + assert(() { + requiredKeys.forEach((key) { + assert(json.containsKey(key), 'Required key "User[$key]" is missing from JSON.'); + assert(json[key] != null, 'Required key "User[$key]" has a null value in JSON.'); + }); + return true; + }()); + return User( id: mapValueOfType(json, r'id'), username: mapValueOfType(json, r'username'), @@ -115,36 +175,50 @@ class User { return null; } - static List listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) => - json is List && json.isNotEmpty - ? json.map(User.fromJson).toList(growable: true == growable) - : true == emptyIsNull ? null : []; + static List? listFromJson(dynamic json, {bool growable = false,}) { + final result = []; + if (json is List && json.isNotEmpty) { + for (final row in json) { + final value = User.fromJson(row); + if (value != null) { + result.add(value); + } + } + } + return result.toList(growable: growable); + } static Map mapFromJson(dynamic json) { final map = {}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) => map[key] = User.fromJson(value)); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = User.fromJson(entry.value); + if (value != null) { + map[entry.key] = value; + } + } } return map; } // maps a json object with a list of User-objects as value to a dart map - static Map> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) { + static Map> mapListFromJson(dynamic json, {bool growable = false,}) { final map = >{}; if (json is Map && json.isNotEmpty) { - json - .cast() - .forEach((key, dynamic value) { - map[key] = User.listFromJson( - value, - emptyIsNull: emptyIsNull, - growable: growable, - ); - }); + json = json.cast(); // ignore: parameter_assignments + for (final entry in json.entries) { + final value = User.listFromJson(entry.value, growable: growable,); + if (value != null) { + map[entry.key] = value; + } + } } return map; } + + /// The list of required keys that must be present in a JSON. + static const requiredKeys = { + }; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/pom.xml b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/pom.xml deleted file mode 100644 index d09de2749f6a..000000000000 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/pom.xml +++ /dev/null @@ -1,73 +0,0 @@ - - 4.0.0 - org.openapitools - Dart2PetstoreClientLibFakeTests - pom - 1.0.0-SNAPSHOT - Dart2 Petstore Client Lib Fake - - - - maven-dependency-plugin - - - package - - copy-dependencies - - - ${project.build.directory} - - - - - - org.codehaus.mojo - exec-maven-plugin - 1.2.1 - - - export-dartfmt - pre-install-test - - exec - - - export - - DART_FMT_PATH=/usr/local/bin/dartfmt - - - - - pub-get - pre-integration-test - - exec - - - pub - - get - - - - - pub-test - integration-test - - exec - - - pub - - run - test - - - - - - - - diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/additional_properties_class_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/additional_properties_class_test.dart index 3f231dddf74d..ba464213ba93 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/additional_properties_class_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/additional_properties_class_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for AdditionalPropertiesClass void main() { - final instance = AdditionalPropertiesClass(); + // final instance = AdditionalPropertiesClass(); group('test AdditionalPropertiesClass', () { // Map mapProperty (default value: const {}) diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/animal_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/animal_test.dart index 3e6526e71957..b4d1e331abee 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/animal_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/animal_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for Animal void main() { - final instance = Animal(); + // final instance = Animal(); group('test Animal', () { // String className diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/another_fake_api_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/another_fake_api_test.dart index 355b4140bdd6..34367effd5a9 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/another_fake_api_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/another_fake_api_test.dart @@ -1,19 +1,21 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 /// tests for AnotherFakeApi void main() { - final instance = AnotherFakeApi(); + // final instance = AnotherFakeApi(); group('tests for AnotherFakeApi', () { // To test special tags diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/api_response_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/api_response_test.dart index b0c30615b926..e9743c1ddded 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/api_response_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/api_response_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for ApiResponse void main() { - final instance = ApiResponse(); + // final instance = ApiResponse(); group('test ApiResponse', () { // int code diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/array_of_array_of_number_only_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/array_of_array_of_number_only_test.dart index 53ed7123a884..16ba1e3e45c3 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/array_of_array_of_number_only_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/array_of_array_of_number_only_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for ArrayOfArrayOfNumberOnly void main() { - final instance = ArrayOfArrayOfNumberOnly(); + // final instance = ArrayOfArrayOfNumberOnly(); group('test ArrayOfArrayOfNumberOnly', () { // List> arrayArrayNumber (default value: const []) diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/array_of_number_only_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/array_of_number_only_test.dart index 99fb4e3ddf79..5a83508f431e 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/array_of_number_only_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/array_of_number_only_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for ArrayOfNumberOnly void main() { - final instance = ArrayOfNumberOnly(); + // final instance = ArrayOfNumberOnly(); group('test ArrayOfNumberOnly', () { // List arrayNumber (default value: const []) diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/array_test_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/array_test_test.dart index f1af158fe2fe..7ed043205d9d 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/array_test_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/array_test_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for ArrayTest void main() { - final instance = ArrayTest(); + // final instance = ArrayTest(); group('test ArrayTest', () { // List arrayOfString (default value: const []) diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/capitalization_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/capitalization_test.dart index c21e1a31c933..ec2cf7e54803 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/capitalization_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/capitalization_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for Capitalization void main() { - final instance = Capitalization(); + // final instance = Capitalization(); group('test Capitalization', () { // String smallCamel diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/cat_all_of_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/cat_all_of_test.dart index f4d0a69b7ca3..018a5e89ce17 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/cat_all_of_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/cat_all_of_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for CatAllOf void main() { - final instance = CatAllOf(); + // final instance = CatAllOf(); group('test CatAllOf', () { // bool declawed diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/cat_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/cat_test.dart index e7d33048bbc4..cb2a70551331 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/cat_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/cat_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for Cat void main() { - final instance = Cat(); + // final instance = Cat(); group('test Cat', () { // String className diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/category_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/category_test.dart index 54d51663d9d9..8e45f5de2e51 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/category_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/category_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for Category void main() { - final instance = Category(); + // final instance = Category(); group('test Category', () { // int id diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/class_model_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/class_model_test.dart index 047ce788765a..0fa269691c11 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/class_model_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/class_model_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for ClassModel void main() { - final instance = ClassModel(); + // final instance = ClassModel(); group('test ClassModel', () { // String class_ diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/default_api_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/default_api_test.dart index 2756c463df1c..530a221d7766 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/default_api_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/default_api_test.dart @@ -1,19 +1,21 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 /// tests for DefaultApi void main() { - final instance = DefaultApi(); + // final instance = DefaultApi(); group('tests for DefaultApi', () { //Future fooGet() async diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/deprecated_object_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/deprecated_object_test.dart index a1c6df250582..cee2bb6a5be3 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/deprecated_object_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/deprecated_object_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for DeprecatedObject void main() { - final instance = DeprecatedObject(); + // final instance = DeprecatedObject(); group('test DeprecatedObject', () { // String name diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/dog_all_of_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/dog_all_of_test.dart index 5a0209898b88..85b1bbc460ad 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/dog_all_of_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/dog_all_of_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for DogAllOf void main() { - final instance = DogAllOf(); + // final instance = DogAllOf(); group('test DogAllOf', () { // String breed diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/dog_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/dog_test.dart index bce7e5bbdece..7704643bc25c 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/dog_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/dog_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for Dog void main() { - final instance = Dog(); + // final instance = Dog(); group('test Dog', () { // String className diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/enum_arrays_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/enum_arrays_test.dart index b3364c9a89a6..07318b4510fe 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/enum_arrays_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/enum_arrays_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for EnumArrays void main() { - final instance = EnumArrays(); + // final instance = EnumArrays(); group('test EnumArrays', () { // String justSymbol diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/enum_class_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/enum_class_test.dart index 496ffbd68cfd..c93a03b32ffa 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/enum_class_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/enum_class_test.dart @@ -1,15 +1,17 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for EnumClass void main() { diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/enum_test_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/enum_test_test.dart index 52618838aff4..a5330759e27a 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/enum_test_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/enum_test_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for EnumTest void main() { - final instance = EnumTest(); + // final instance = EnumTest(); group('test EnumTest', () { // String enumString diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/fake_api_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/fake_api_test.dart index 065e89afdc1e..0b0c6bcb8ac0 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/fake_api_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/fake_api_test.dart @@ -1,19 +1,21 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 /// tests for FakeApi void main() { - final instance = FakeApi(); + // final instance = FakeApi(); group('tests for FakeApi', () { // Health check endpoint @@ -65,7 +67,14 @@ void main() { // TODO }); - // For this test, the body for this request much reference a schema named `File`. + // For this test, the body has to be a binary file. + // + //Future testBodyWithBinary(MultipartFile body) async + test('test testBodyWithBinary', () async { + // TODO + }); + + // For this test, the body for this request must reference a schema named `File`. // //Future testBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass) async test('test testBodyWithFileSchema', () async { @@ -129,7 +138,7 @@ void main() { // To test the collection format in query parameters // - //Future testQueryParameterCollectionFormat(List pipe, List ioutil, List http, List url, List context) async + //Future testQueryParameterCollectionFormat(List pipe, List ioutil, List http, List url, List context, String allowEmpty, { Map language }) async test('test testQueryParameterCollectionFormat', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/fake_classname_tags123_api_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/fake_classname_tags123_api_test.dart index 1a0f96589476..2570d74f567c 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/fake_classname_tags123_api_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/fake_classname_tags123_api_test.dart @@ -1,19 +1,21 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 /// tests for FakeClassnameTags123Api void main() { - final instance = FakeClassnameTags123Api(); + // final instance = FakeClassnameTags123Api(); group('tests for FakeClassnameTags123Api', () { // To test class name in snake case diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/file_schema_test_class_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/file_schema_test_class_test.dart index 4316bb385a76..b69c027e926a 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/file_schema_test_class_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/file_schema_test_class_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for FileSchemaTestClass void main() { - final instance = FileSchemaTestClass(); + // final instance = FileSchemaTestClass(); group('test FileSchemaTestClass', () { // ModelFile file diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/foo_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/foo_test.dart index 7b72da51b0e8..82ac0359b8a6 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/foo_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/foo_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for Foo void main() { - final instance = Foo(); + // final instance = Foo(); group('test Foo', () { // String bar (default value: 'bar') diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/format_test_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/format_test_test.dart index e776be1d9f68..5f382b03b5bf 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/format_test_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/format_test_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for FormatTest void main() { - final instance = FormatTest(); + // final instance = FormatTest(); group('test FormatTest', () { // int integer diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/has_only_read_only_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/has_only_read_only_test.dart index 16b36e117094..b41796d19d62 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/has_only_read_only_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/has_only_read_only_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for HasOnlyReadOnly void main() { - final instance = HasOnlyReadOnly(); + // final instance = HasOnlyReadOnly(); group('test HasOnlyReadOnly', () { // String bar diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/health_check_result_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/health_check_result_test.dart index 1599fc46a283..5f09d312d74d 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/health_check_result_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/health_check_result_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for HealthCheckResult void main() { - final instance = HealthCheckResult(); + // final instance = HealthCheckResult(); group('test HealthCheckResult', () { // String nullableMessage diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/inline_response_default_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/inline_response_default_test.dart index ecb2a874f05f..e344b8a6fd00 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/inline_response_default_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/inline_response_default_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for InlineResponseDefault void main() { - final instance = InlineResponseDefault(); + // final instance = InlineResponseDefault(); group('test InlineResponseDefault', () { // Foo string diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/map_test_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/map_test_test.dart index 21af0b85fa36..f7da040f3265 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/map_test_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/map_test_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for MapTest void main() { - final instance = MapTest(); + // final instance = MapTest(); group('test MapTest', () { // Map> mapMapOfString (default value: const {}) diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/mixed_properties_and_additional_properties_class_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/mixed_properties_and_additional_properties_class_test.dart index a8e0fdd8da64..f23f59f58c72 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/mixed_properties_and_additional_properties_class_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/mixed_properties_and_additional_properties_class_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for MixedPropertiesAndAdditionalPropertiesClass void main() { - final instance = MixedPropertiesAndAdditionalPropertiesClass(); + // final instance = MixedPropertiesAndAdditionalPropertiesClass(); group('test MixedPropertiesAndAdditionalPropertiesClass', () { // String uuid diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/model200_response_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/model200_response_test.dart index c28d3671dfc1..46ccb12c5586 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/model200_response_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/model200_response_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for Model200Response void main() { - final instance = Model200Response(); + // final instance = Model200Response(); group('test Model200Response', () { // int name diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/model_client_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/model_client_test.dart index c0a59729e3d5..e730318e0679 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/model_client_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/model_client_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for ModelClient void main() { - final instance = ModelClient(); + // final instance = ModelClient(); group('test ModelClient', () { // String client diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/model_file_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/model_file_test.dart index b2f6d48afa74..663e0a76fb75 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/model_file_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/model_file_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for ModelFile void main() { - final instance = ModelFile(); + // final instance = ModelFile(); group('test ModelFile', () { // Test capitalization diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/model_list_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/model_list_test.dart index 02e98011b21f..1300f29e4947 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/model_list_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/model_list_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for ModelList void main() { - final instance = ModelList(); + // final instance = ModelList(); group('test ModelList', () { // String n123list diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/model_return_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/model_return_test.dart index b7f065e4fb45..525c88715ac4 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/model_return_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/model_return_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for ModelReturn void main() { - final instance = ModelReturn(); + // final instance = ModelReturn(); group('test ModelReturn', () { // int return_ diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/name_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/name_test.dart index 8e0ef41e9f2f..0d92245332bf 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/name_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/name_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for Name void main() { - final instance = Name(); + // final instance = Name(); group('test Name', () { // int name diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/nullable_class_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/nullable_class_test.dart index 6147fbe1336b..269e281027ba 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/nullable_class_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/nullable_class_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for NullableClass void main() { - final instance = NullableClass(); + // final instance = NullableClass(); group('test NullableClass', () { // int integerProp diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/number_only_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/number_only_test.dart index 3662bff150d9..04381ff2c543 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/number_only_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/number_only_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for NumberOnly void main() { - final instance = NumberOnly(); + // final instance = NumberOnly(); group('test NumberOnly', () { // num justNumber diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/object_with_deprecated_fields_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/object_with_deprecated_fields_test.dart index b5769dc67490..46275670a17a 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/object_with_deprecated_fields_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/object_with_deprecated_fields_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for ObjectWithDeprecatedFields void main() { - final instance = ObjectWithDeprecatedFields(); + // final instance = ObjectWithDeprecatedFields(); group('test ObjectWithDeprecatedFields', () { // String uuid diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/order_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/order_test.dart index 614a14e42bb9..b625abdaf9fc 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/order_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/order_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for Order void main() { - final instance = Order(); + // final instance = Order(); group('test Order', () { // int id diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/outer_composite_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/outer_composite_test.dart index 294c823443c3..33fe3a7ef1a6 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/outer_composite_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/outer_composite_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for OuterComposite void main() { - final instance = OuterComposite(); + // final instance = OuterComposite(); group('test OuterComposite', () { // num myNumber diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/outer_enum_default_value_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/outer_enum_default_value_test.dart index 84ae975ef189..fa0e93aaf7b0 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/outer_enum_default_value_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/outer_enum_default_value_test.dart @@ -1,15 +1,17 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for OuterEnumDefaultValue void main() { diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/outer_enum_integer_default_value_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/outer_enum_integer_default_value_test.dart index bf3399ba4281..6d88d2c3d159 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/outer_enum_integer_default_value_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/outer_enum_integer_default_value_test.dart @@ -1,15 +1,17 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for OuterEnumIntegerDefaultValue void main() { diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/outer_enum_integer_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/outer_enum_integer_test.dart index d807f03227ff..41715de4de58 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/outer_enum_integer_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/outer_enum_integer_test.dart @@ -1,15 +1,17 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for OuterEnumInteger void main() { diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/outer_enum_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/outer_enum_test.dart index a2b79ce0c1c6..100df39ba80e 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/outer_enum_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/outer_enum_test.dart @@ -1,15 +1,17 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for OuterEnum void main() { diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/outer_object_with_enum_property_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/outer_object_with_enum_property_test.dart index 6995c37ebb4c..ffb9f4019c9a 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/outer_object_with_enum_property_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/outer_object_with_enum_property_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for OuterObjectWithEnumProperty void main() { - final instance = OuterObjectWithEnumProperty(); + // final instance = OuterObjectWithEnumProperty(); group('test OuterObjectWithEnumProperty', () { // OuterEnumInteger value diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/pet_api_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/pet_api_test.dart index 5f4c994acefa..939365f0f382 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/pet_api_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/pet_api_test.dart @@ -1,19 +1,21 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 /// tests for PetApi void main() { - final instance = PetApi(); + // final instance = PetApi(); group('tests for PetApi', () { // Add a new pet to the store diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/pet_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/pet_test.dart index 23c26595c85c..8db1ddea4ec6 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/pet_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/pet_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for Pet void main() { - final instance = Pet(); + // final instance = Pet(); group('test Pet', () { // int id diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/read_only_first_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/read_only_first_test.dart index d3326fd494d0..16d3a5662597 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/read_only_first_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/read_only_first_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for ReadOnlyFirst void main() { - final instance = ReadOnlyFirst(); + // final instance = ReadOnlyFirst(); group('test ReadOnlyFirst', () { // String bar diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/special_model_name_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/special_model_name_test.dart index f3b461364fbe..4b00f426a86c 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/special_model_name_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/special_model_name_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for SpecialModelName void main() { - final instance = SpecialModelName(); + // final instance = SpecialModelName(); group('test SpecialModelName', () { // int dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/store_api_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/store_api_test.dart index 4a7ed54abbbc..351ef2682801 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/store_api_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/store_api_test.dart @@ -1,19 +1,21 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 /// tests for StoreApi void main() { - final instance = StoreApi(); + // final instance = StoreApi(); group('tests for StoreApi', () { // Delete purchase order by ID diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/tag_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/tag_test.dart index 66ecdfe488dc..78d5880e6d4c 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/tag_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/tag_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for Tag void main() { - final instance = Tag(); + // final instance = Tag(); group('test Tag', () { // int id diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/user_api_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/user_api_test.dart index 73ee89a29451..4f82364bd172 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/user_api_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/user_api_test.dart @@ -1,19 +1,21 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 /// tests for UserApi void main() { - final instance = UserApi(); + // final instance = UserApi(); group('tests for UserApi', () { // Create user diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/user_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/user_test.dart index b89cd360489d..d86551e10b64 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/user_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/test/user_test.dart @@ -1,18 +1,20 @@ // // AUTO-GENERATED FILE, DO NOT MODIFY! // -// @dart=2.0 +// @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first +// ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; +// these tests are not regenerated by dart 2 generator as they break compatibility with Dart versions under 2.12 // tests for User void main() { - final instance = User(); + // final instance = User(); group('test User', () { // int id