@@ -356,29 +356,59 @@ Code _printToJson(PrintContext context, Iterable<ContextProperty> properties) {
356356 ))
357357 .statement,
358358 for (final property in properties) ...[
359- if (! property.isRequired)
360- Code (
361- 'if(${kDataVariableName }.containsKey(\' ${property .name .value }\' )) {' ),
362- declareFinal (context.namePrinter.printLocalPropertyName (property.name))
363- .assign (refer (context.namePrinter.printPropertyName (property.name)))
364- .statement,
365- refer (resultDataVariableName)
366- .index (literalString (property.name.value))
367- .assign (
368- printToJsonValueOnExpression (
369- context,
370- property,
371- printMaybeAddCast (
372- refer (
373- context.namePrinter.printLocalPropertyName (property.name),
359+ if (context.context.config.allowMissingNullableKeysInFromJson &&
360+ ! property.isNonNull) ...[
361+ // For nullable properties when allowMissingNullableKeysInFromJson is true
362+ declareFinal (context.namePrinter.printLocalPropertyName (property.name))
363+ .assign (refer (kDataVariableName)
364+ .property ('containsKey' )
365+ .call ([literalString (property.name.value)]).conditional (
366+ refer (context.namePrinter.printPropertyName (property.name)),
367+ literalNull,
368+ ))
369+ .statement,
370+ refer (resultDataVariableName)
371+ .index (literalString (property.name.value))
372+ .assign (
373+ printToJsonValueOnExpression (
374+ context,
375+ property,
376+ printMaybeAddCast (
377+ refer (
378+ context.namePrinter.printLocalPropertyName (property.name),
379+ ),
380+ property.hasDefaultValue && property.isNonNull,
381+ printClassPropertyType (context, property),
374382 ),
375- property.hasDefaultValue && property.isNonNull,
376- printClassPropertyType (context, property),
377383 ),
378- ),
379- )
380- .statement,
381- if (! property.isRequired) Code ('}' ),
384+ )
385+ .statement,
386+ ] else ...[
387+ // Original logic for required properties or when allowMissingNullableKeysInFromJson is false
388+ if (! property.isRequired)
389+ Code (
390+ 'if(${kDataVariableName }.containsKey(\' ${property .name .value }\' )) {' ),
391+ declareFinal (context.namePrinter.printLocalPropertyName (property.name))
392+ .assign (refer (context.namePrinter.printPropertyName (property.name)))
393+ .statement,
394+ refer (resultDataVariableName)
395+ .index (literalString (property.name.value))
396+ .assign (
397+ printToJsonValueOnExpression (
398+ context,
399+ property,
400+ printMaybeAddCast (
401+ refer (
402+ context.namePrinter.printLocalPropertyName (property.name),
403+ ),
404+ property.hasDefaultValue && property.isNonNull,
405+ printClassPropertyType (context, property),
406+ ),
407+ ),
408+ )
409+ .statement,
410+ if (! property.isRequired) Code ('}' ),
411+ ]
382412 ],
383413 refer (resultDataVariableName).returned.statement,
384414 ]);
0 commit comments