Skip to content

Commit

Permalink
Merge pull request #28 from iamarnas/master
Browse files Browse the repository at this point in the history
Added Dart null safety.
  • Loading branch information
iamarnas authored Apr 14, 2021
2 parents b254656 + d59eb0b commit 1b5b829
Show file tree
Hide file tree
Showing 8 changed files with 356 additions and 174 deletions.
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,17 @@

## [Released]

## [3.1.0] - 2021-04-14

### Added

- see [pull request](https://github.com/hiranthaR/Json-to-Dart-Model/pull/28) from [Arnas](https://github.com/iamarnas)
- Added support for Dart null safety.

> For any suggestions on how to improve the better null safety syntax your are welcome to open [discuss](https://github.com/hiranthaR/Json-to-Dart-Model/discussions).
- Those who update to 3.1.0 from older version. Be sure to add `"nullSafety": false,` to `models.jsonc` configuration or go to help for more information if you were warned.

## [3.0.3] - 2021-04-06

### Added
Expand Down
47 changes: 33 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,16 @@
</p>

<p align="center">
<a href="https://marketplace.visualstudio.com/items?itemName=hirantha.json-to-dart"><img src="https://vsmarketplacebadge.apphb.com/version/hirantha.json-to-dart.svg?style=flat-square" alt="Version"></a>
<a href="https://marketplace.visualstudio.com/items?itemName=hirantha.json-to-dart"><img src="https://vsmarketplacebadge.apphb.com/installs/hirantha.json-to-dart.svg?style=flat-square" alt="Install"></a>
<a href="https://marketplace.visualstudio.com/items?itemName=hirantha.json-to-dart"><img src="https://vsmarketplacebadge.apphb.com/downloads/hirantha.json-to-dart.svg?style=flat-square" alt="Download"></a>
<a href="https://www.hirantha.xyz"><img src="https://img.shields.io/badge/Ask%20me-anything-1abc9c.svg?style=flat-square" alt="Ask Me Anything"></a>
<a href="https://github.com/hiranthaR/Json-to-Dart-Model/issues"><img src="https://img.shields.io/github/issues/hiranthaR/Json-to-Dart-Model?logo=github&style=flat-square" alt="Issues"></a>
<a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/license-MIT-orange.svg?style=flat-square" alt="License: MIT"></a>
<a href="https://dart.dev/guides/language/effective-dart/style"><img src="https://img.shields.io/badge/style-Effective%20Dart-blue?style=flat-square" alt="Effective Dart Style"></a>
<a href="https://github.com/rrousselGit/freezed"><img src="https://img.shields.io/badge/supports-Freezed-blue?style=flat-square" alt="Freezed"></a>
<a href="https://github.com/google/json_serializable.dart/tree/master/json_serializable"><img src="https://img.shields.io/badge/supports-Json_Serializable-blue?style=flat-square" alt="Json Serializable"></a>
<a href="https://marketplace.visualstudio.com/items?itemName=hirantha.json-to-dart"><img src="https://vsmarketplacebadge.apphb.com/version/hirantha.json-to-dart.svg?labelColor=009903&style=flat-square" alt="Version"></a>
<a href="https://marketplace.visualstudio.com/items?itemName=hirantha.json-to-dart"><img src="https://vsmarketplacebadge.apphb.com/installs/hirantha.json-to-dart.svg?label=Installs&labelColor=009903&style=flat-square" alt="Install"></a>
<a href="https://marketplace.visualstudio.com/items?itemName=hirantha.json-to-dart"><img src="https://vsmarketplacebadge.apphb.com/downloads/hirantha.json-to-dart.svg?label=Downloads&labelColor=009903&style=flat-square" alt="Download"></a>
<a href="https://www.hirantha.xyz"><img src="https://img.shields.io/badge/Ask%20Me-Anything-1abc9c.svg?labelColor=007d80&style=flat-square" alt="Ask Me Anything"></a>
<a href="https://github.com/hiranthaR/Json-to-Dart-Model/issues"><img src="https://img.shields.io/github/issues/hiranthaR/Json-to-Dart-Model?label=Issues&labelColor=c95149&logo=github&color=ff5b4f&style=flat-square" alt="Issues"></a>
<a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-orange.svg?labelColor=d67c15&style=flat-square" alt="License: MIT"></a>
<a href="https://dart.dev/guides/language/effective-dart/style"><img src="https://img.shields.io/badge/Style-Effective%20Dart-blue?labelColor=005f96&style=flat-square" alt="Effective Dart Style"></a>
<a href="https://github.com/rrousselGit/freezed"><img src="https://img.shields.io/badge/Supports-Freezed-blue?labelColor=005f96&style=flat-square" alt="Freezed"></a>
<a href="https://github.com/google/json_serializable.dart/tree/master/json_serializable"><img src="https://img.shields.io/badge/Supports-Json_Serializable-blue?labelColor=005f96&style=flat-square" alt="Json Serializable"></a>
<a href="https://dart.dev/null-safety"><img src="https://img.shields.io/badge/Dart-Null_Safety-blue?labelColor=005f96&style=flat-square&logo=Dart" alt="Null Safety"></a>
</p>

> From JSON to Dart advanced
Expand All @@ -31,10 +32,11 @@
<li>
<a href="#the-syntax">The Syntax</a>
<ul>
<li><a href="#to-string-method">To String method</a></li>
<li><a href="#copyWith-method">CopyWith method</a></li>
<li><a href="#to-string-method">toString method</a></li>
<li><a href="#copyWith-method">copyWith method</a></li>
<li><a href="#equality-operator">Equality Operator</a></li>
<li><a href="#equatable">Equatable</a></li>
<li><a href="#null-safety">Null safety</a></li>
</ul>
</li>
<li><a href="#supported-generators">Supported Generators</a></li>
Expand Down Expand Up @@ -97,7 +99,7 @@ To customise your classes is very easy. If you want fast create a simple class t

- Convert your all json objects from the file.

`Json to Dart Model` generator keep all your json objects in the file with name `models.jsonc` and allows you to configure your classes according to you preferences. `models.jsonc` content is a list that contains all of your json objects that will later be converted to `Dart` classes. You can share this file with your friends and help them create better code. The `jsonc` format allows you to comment on your json objects to easily find them later or make it easier to explain to your team. To create the `models.jsonc` file you can run command in the command palette `Build Models` or use keys bingning `Shift + Ctrl + Alt + B` and you will be asked if you want create file, choose `Yes` and hit `Enter`. After adding file open it to read detailed instructions on how it works.
`Json to Dart Model` generator keep all your json objects in the file with name `models.jsonc` and allows you to configure your classes according to you preferences. `models.jsonc` content is a list that contains all of your json objects that will later be converted to `Dart` classes. You can share this file with your friends and help them create better code. The `jsonc` format allows you to comment on your json objects to easily find them later or make it easier to explain to your team. To create the `models.jsonc` file you can run command in the command palette `Build Models` or use keys bingning `Shift + Ctrl + Alt + B` and you will be asked if you want create file, hit `Enter` to add file. After adding file open it to read detailed instructions on how it works.

Create file manually. Add new file to your app directory `my_app/models.jsonc` and add configuration object.

Expand All @@ -120,6 +122,8 @@ Create file manually. Add new file to your app directory `my_app/models.jsonc` a
"copyWith": false,
// Add equality operator.
"equality": false,
// Indicate that a variable can have the value null.
"nullSafety": false,
// Default target directory.
"targetDirectory": "/lib/models",
// Disable ask for confirmation to start the conversion.
Expand Down Expand Up @@ -152,6 +156,7 @@ Your final result should look like this:
"toString": false,
"copyWith": false,
"equality": false,
"nullSafety": false,
"targetDirectory": "/lib/models",
"fastMode": false
},
Expand Down Expand Up @@ -185,7 +190,7 @@ Add serializing JSON using code generation libraries to `pubspec.yaml`.
## Freezed
Freezed requires three packages to generate json files to Freezed classes with a few clicks.
Freezed supports both old versions to 0.12.7 and new from 0.14.0 and higher. Freezed requires three packages to generate json files to Freezed classes with a few clicks.
structure of the `pubspec.yaml`

Expand All @@ -204,9 +209,10 @@ Freezed requires three packages to generate json files to Freezed classes with a
All generated classes with Freezed will be `@immutable` and support all methods like [copyWith](#copyWith-method), [toString](#to-string-method), [equality operator](#equality-operator)`==`... See example:

```dart
// Examples are for Freezed up to version 0.12.7
@freezed
abstract class Address with _$Address {
const factory Address({
factory Address({
@JsonKey(name: "street") String street,
@JsonKey(name: "suite") String suite,
@JsonKey(name: "city") String city,
Expand All @@ -217,6 +223,7 @@ abstract class Address with _$Address {
factory Address.fromJson(Map<String, dynamic> json) => _$AddressFromJson(json);
}
```

Freezed generator are useful for who work daily with coding. All you have to do is upgrade some values and Freezed will takecare of the rest. Your don't need worry about that you have forget update parser to some method. More what you can do withFreezed read [freezed documentation](https://pub.dev/packages/freezed).

**TIP:** If you think that you have too much generated files you can look at tips by Freezed how to [ignore lint warnings on generated files](https://pub.dev/packages/freezed#ignore-lint-warnings-on-generated-files).
Expand Down Expand Up @@ -296,6 +303,12 @@ String toString() {
return 'Todos(userId: $userId, id: $id, title: $title, completed: $completed)';
}
```
Equatable can implement [toString](https://github.com/felangel/equatable/blob/master/README.md#tostring-implementation) method including all the given props. If Equatable support enabled then will implement Equatable `toString` Implementation.

```dart
@override
bool get stringify => true;
```

## CopyWith method

Expand All @@ -317,6 +330,12 @@ Todos copyWith({
}
```

## Null Safety

If `null safety` enabled it will indicate that a variable may have the value `null`. Required in the new `Dart` language from version 2.12...

> **Note:** Before enable null safety make sure your packages also support Dart null safety.

## Serializing JSON using code generation libraries

If you'd like to use Code Generation Libraries from **Flutter**, first of all I suggest you to add dependencies to the `pubspec.yaml` file. It also can be done with this extension. You don't need to worry about it :wink:.
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 6 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "json-to-dart",
"displayName": "Json to Dart Model",
"description": "Extension convert Json to Dart Model class",
"version": "3.0.4",
"version": "3.1.0",
"publisher": "hirantha",
"icon": "icon.png",
"engines": {
Expand All @@ -15,7 +15,10 @@
"flutter",
"json",
"freezed",
"serializing"
"serializing",
"null safety",
"null",
"safety"
],
"categories": [
"Other"
Expand Down Expand Up @@ -123,4 +126,4 @@
"lodash": "^4.17.19",
"mkdirp": "^1.0.3"
}
}
}
32 changes: 28 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,13 @@ async function transformFromSelection(uri: Uri) {
getSelectedText()
.then(validateLength)
.then((json) =>
generateClass(new InputSettings(className, <string>targetDirectory, json, true, input)))
generateClass(new InputSettings(
className,
<string>targetDirectory,
json,
false,
input
)))
.catch(handleError);
}

Expand Down Expand Up @@ -201,7 +207,13 @@ async function transformFromSelectionToCodeGen(uri: Uri) {
getSelectedText()
.then(validateLength)
.then((json) =>
generateClass(new InputSettings(className, <string>targetDirectory, json, true, input)))
generateClass(new InputSettings(
className,
<string>targetDirectory,
json,
true,
input
)))
.then((_) => runGenerator()).catch(handleError);
}

Expand Down Expand Up @@ -231,7 +243,13 @@ async function transformFromClipboard(uri: Uri) {
getClipboardText()
.then(validateLength)
.then((json) =>
generateClass(new InputSettings(className, <string>targetDirectory, json, true, input)))
generateClass(new InputSettings(
className,
<string>targetDirectory,
json,
false,
input
)))
.catch(handleError);
}

Expand Down Expand Up @@ -261,7 +279,13 @@ async function transformFromClipboardToCodeGen(uri: Uri) {
getClipboardText()
.then(validateLength)
.then((json) =>
generateClass(new InputSettings(className, <string>targetDirectory, json, true, input)))
generateClass(new InputSettings(
className,
<string>targetDirectory,
json,
true,
input
)))
.then((_) => runGenerator()).catch(handleError);
}

Expand Down
31 changes: 29 additions & 2 deletions src/input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ interface InputInterface {
* Required root path.
*/
targetDirectory: string;
nullSafety: boolean;
fastMode: boolean;
}

Expand All @@ -26,6 +27,7 @@ export class Input implements InputInterface {
copyWith: boolean = false;
equality: boolean = false;
generate: boolean = false;
nullSafety: boolean = false;
targetDirectory: string = '/lib/models';
fastMode: boolean = false;

Expand All @@ -37,6 +39,7 @@ export class Input implements InputInterface {
this.copyWith = obj.copyWith;
this.equality = obj.equality;
this.generate = obj.serializable;
this.nullSafety = obj.nullSafety;
this.targetDirectory = obj.targetDirectory;
this.fastMode = obj.fastMode;
}
Expand All @@ -55,7 +58,12 @@ export async function getUserInput(generate: boolean = false): Promise<Input> {

input.generate = generate;

if (generate) { input.freezed = await askForFreezed(); }
if (generate) {
input.freezed = await askForFreezed();
if (input.freezed) {
input.nullSafety = await askForNullSafety();
}
}
// Freezed supports all the methods and you do not have to ask the user about the rest.
if (!input.freezed) {
input.equatable = await askForEquatableCompatibility();
Expand All @@ -65,8 +73,8 @@ export async function getUserInput(generate: boolean = false): Promise<Input> {
}
input.toString = await askForToStringMethod();
input.copyWith = await askForCopyWithMethod();
input.nullSafety = await askForNullSafety();
}

return input;
}
/**
Expand Down Expand Up @@ -195,3 +203,22 @@ async function askForEqualityOperator(): Promise<boolean> {
}
}

async function askForNullSafety(): Promise<boolean> {
const selection = await window.showQuickPick(
[
{
label: "No",
picked: true,
},
{ label: "Yes" },
],
{ placeHolder: "Enable support for Dart null safety?" }
);

switch (selection?.label) {
case "Yes":
return true;
default:
return false;
}
}
2 changes: 2 additions & 0 deletions src/models_file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ export class Models {
sb += printLine('"copyWith": false,', true, 2);
sb += printLine('// Add equality operator.', true, 2);
sb += printLine('"equality": false,', true, 2);
sb += printLine('// Indicate that a variable can have the value null.', true, 2);
sb += printLine('"nullSafety": false,', true, 2);
sb += printLine('// Default target directory.', true, 2);
sb += printLine('"targetDirectory": "/lib/models",', true, 2);
sb += printLine('// Disable ask for confirmation to start the conversion.', true, 2);
Expand Down
Loading

0 comments on commit 1b5b829

Please sign in to comment.