google / google/json_serializable.dart

Default values are not given the appropiate scope

Open
#946 1 comment 2 reactions 0 assignees View on GitHub
State: blocked Type: bug
Dominant language
Dart
Stars
1.6k
Forks
461
Avg merge
45m
Merged PRs (30d)
1

Description

## Dart version

```
$ dart --version
Dart SDK version: 2.13.1 (stable) (Fri May 21 12:45:36 2021 +0200) on "linux_x64"
```

(I'm aware that this is slightly out of date, but I don't believe this should affect json_serializable).

Consider I create `lib/tst.dart` with the following:

```dart
import 'package:json_annotation/json_annotation.dart';

part 'tst.g.dart';

@JsonSerializable()
class Test {
static const defaultValue = 'default';

final String thing;
Test({this.thing = defaultValue});
}
```

Trying to use this from anywhere results in:

```
lib/tst.g.dart:10:42: Error: Getter not found: 'defaultValue'.
thing: json['thing'] as String? ?? defaultValue,
^^^^^^^^^^^^
```

The reason is evident if we examine `tst.g.dart`:

```dart
// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'tst.dart';

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

Test _$TestFromJson(Map json) => Test(
thing: json['thing'] as String? ?? defaultValue,
);

Map _$TestToJson(Test instance) => {
'thing': instance.thing,
};
```

`defaultValue` is a member of the `Test` class, but the name is used bare here, and it should be `Test.defaultValue`.

This can be easily worked around by setting the default to `Test.defaultValue` in `tst.dart`, but I figured this is probably still a `json_serializable` bug that's worth filing.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.