Skip to content

Code generation for complex types with default value produces warning #1170

@guenth39

Description

@guenth39

When having a constructor with a not nullable parameter that is a complex type and has a default value, flutter gives me the following warning:

: Warning: Operand of null-aware operation '??' has type 'Duration' which excludes null.
lib/model/my_class.g.dart:13
 - 'Duration' is from 'dart:core'.
      d: Duration(microseconds: json['d'] as int) ?? Duration.zero,

See the following example code to reproduce it:

part 'my_class.g.dart';

@JsonSerializable()
class MyClass {
  const MyClass({
    required this.a,
    required this.c,
    this.b = '',
    this.d = Duration.zero,
  });

  factory MyClass.fromJson(Map<String, dynamic> json) =>
      _$MyClassFromJson(json);

  final String a, b;
  final Duration c, d;

  Map<String, dynamic> toJson() => _$MyClassToJson(this);
}
// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'my_class.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

MyClass _$MyClassFromJson(Map<String, dynamic> json) => MyClass(
      a: json['a'] as String,
      c: Duration(microseconds: json['c'] as int),
      b: json['b'] as String? ?? '',
      d: Duration(microseconds: json['d'] as int) ?? Duration.zero,
    );

Map<String, dynamic> _$MyClassToJson(MyClass instance) => <String, dynamic>{
      'a': instance.a,
      'b': instance.b,
      'c': instance.c.inMicroseconds,
      'd': instance.d.inMicroseconds,
    };

flutter --version

Flutter 3.0.2 • channel stable • https://github.com/flutter/flutter.git
Framework • revision cd41fdd495 (vor 4 Wochen) • 2022-06-08 09:52:13 -0700
Engine • revision f15f824b57
Tools • Dart 2.17.3 • DevTools 2.12.2

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions