JsonToDartRelated articles

  • Flutter’s most versatile JsonToDart tool (Desktop Web Sea, Land and Air support)
  • Flutter JsonToDart LEI for Mac is not really mark
  • Flutter JsonToDart tools

2020-05-04 Update to UWP: Added the switch on whether to format Dart or not.

I have been making Flutter for nearly one and a half years, from the beginning it is dry

I’m still writing code that pays attention to specifications, performance, comments, all kinds of details. A good tool can improve our work efficiency,

JsonToDart is updated with the following considerations:

  • The dart code was generated quickly for ease of development, without much attention to the DART code specification.
  • Previous versions used go-flutter to generate the final product due to the imperfections of the Flutter desktop. The Flutter SDK version has come to 1.18, the desktop features are further improved, and it is time to recompile for a new wave
  • Github is too slow in China, so consider moving the installation package and web version to Gitee for everyone to use

Download and install

  • UWP Microsoft store I put Microsoft store this time, Windows10 Windows buddy suggested using this, if the update is also automatic. Click on the link or open the Microsoft Store to search for JsonToDart.

  • WPF for Windows7, 8 Windows users prepared the WPF version of the installation package

  • UWP for Windows10 if the Microsoft store is having a hard time, you can download the installation package directly here. See the previous article for installation methods

  • A wave of Flutter for Macos can be used to download the app

  • Lazy to install Flutter for Web? Well, there is a web version here, but it is recommended to use other versions, js can not distinguish between double and int, if you must use it, it is suggested to turn on the full protection of data type, please see the details later

use

On the left is the JSON input box and the resulting Dart code, and on the right is the structure of the generated JSON class

formatting

Click the format button to convert the JSON to the json class structure visualized on the right

More Settings

All Settings will be saved automatically, except for the Flutter version, which needs to be saved manually. I haven’t found the exit time yet.

Full data type protection

There must be times when you are stuck on the server side, right? Json parsing fails because the specified data type is not passed.

Turning this switch on adds a layer of protection when retrieving data, as shown below

T asT<T>(dynamic value) {
  if (value is T) {
    return value;
  }
  if(value ! =null) {
    final String valueS = value.toString();
    if (0 is T) {
      return int.tryParse(valueS) as T;
    } else if (0.0 is T) {
      return double.tryParse(valueS) as T;
    } else if (' ' is T) {
      return valueS as T;
    } else if (false is T) {
      if (valueS == '0' || valueS == '1') {
        return (valueS == '1') as T;
      }
      return bool.fromEnvironment(value.toString()) asT; }}return null;
}
Copy the code

Array omnidirectional protection

Have you ever been in a situation where one error caused the entire parsing of json to fail while looping through an array?

Turning this switch on protects each loop parse, as shown below

void tryCatch(Function f) {
  try{ f? .call(); }catch (e, stack) {
    debugPrint("$e");
    debugPrint("$stack"); }}Copy the code

Number of times to traverse a number of groups

In the data returned by the server, sometimes not every item in the array has all the attributes,

If only the first one is checked, the attribute is lost

You can avoid losing attributes by looping multiple times

The choices are 1,20,99

99 means the loop is all checked

Attribute name

Dart naming convention

Attribute naming convention options:

  • Remain the same
  • Hump named the little hump josnToDart
  • PASCAL named the big hump JsonToDart
  • The Hungarian named underscore jSON_to_dart

Dart officially recommends hump naming for small humps

Attributes sorting

Sort attributes

Sorting options:

  • Remain the same
  • Ascending order
  • Descending order

Adding a Protection Method

Whether to add a protection method. Data type omni-protection/Array omni-protection both generate methods when enabled. Open it the first time you use it, and you can put it in a Dart file (with a reference in the header). There’s no need to turn it on later when it’s generated.

File header information

You can add copyright, improt Dart, creator information, etc., to this function. You can use [Date YYYY MM-DD] to generate the time.

For example, [Date YYYY MM-DD] will generate the time when you generated the Dart code in YYYY MM-DD format

Property accessor type

After hitting Format, a visual JSON class structure is displayed on the right, and property accessor type Settings are displayed in the right column

Options:

  • The default
  • Final
  • Get
  • GetSet

The top Settings are changed, and the subitems are changed. You can also set individual properties.

Modify the JSON information

After hitting Format, the right side displays a visual JSON class structure.

The first column is the corresponding key in JSON

The second column is the name of the attribute type/class. If it is a class name, it is indicated with a yellow background

The third column contains the name of the property, and if the input option is empty, a red prompt is displayed

The fourth column is the accessor type of the property

Generate the Dart

After you’ve set it up, click the Generate Dart button, and the Dart code you want will be generated on the left, with the message “Dart generated successfully, copied to clipboard”, ready to be copied directly to your Dart file

Take a chestnut

For example, in business, Person has a name and an age

import 'dart:convert';
import 'util.dart';
part 'person_part.dart';

class Person {
  Person({
    this.age,
    this.name,
  });

  factory Person.fromJson(Map<String.dynamic> jsonRes) =>
      Person(age: asT<int>(jsonRes['age']), name: asT<String>(jsonRes['name']));

  final int age;
  final String name;

  Map<String.dynamic> toJson() => <String.dynamic> {'age': age,
        'name': name,
      };

  @override
  String toString() {
    return json.encode(this); }}Copy the code

Now you have business logic on the front end, and you need to know if this person is a child, a young person, or an old person. So what should we do? Let’s just write it in this class, right?

Sure, but if the server changes the data model later and we use tools to generate code copies directly, won’t our business code be lost?

As luck would have it

Dart provides us with the extension extension you need

  • Set the DART SDK >=2.6
environment:
  sdk: '> = server < 3.0.0'
Copy the code
  • Create an analysis_options.yaml file in the Flutter project root and add the following contents to the file.
analyzer:
    enable-experiment:
        - extension-methods
Copy the code

And then you can do this.

part of 'person.dart';

enum AgeType {
  baby,
  youth,
  old,
}

extension PersonE on Person {
  AgeType get ageType {
    if (age < 5) {
      return AgeType.baby;
    } else if (age < 50) {
      return AgeType.youth;
    }
    returnAgeType.old; }}Copy the code

This way, when you change your Person metadata model, you don’t need to rewrite the business logic you wrote, you just need to run the tool again.

insufficient

  • For scenarios where attributes need to be modified, usemixinBlending in or simply setting this property to writable still doesn’t get rid of it
mixin PersonMixin  {
   int currentAge;
}
Copy the code
  • When parsing JSON, parse different data models according to different situations, which is often asked whether generics are supported. As saying. The e server returns a different data type model for the same interface.

The worst thing is that the code is written into the metadata model, and the next update will have to be handwritten. Simple model is ok, big model thousands of line, really is drunk.

  • Dart does not support partial splitting of classes. Not sure when DART will be supported.

Packaging process

The whole package is in Flutter 1.18, also record the process.

Flutter for Windows

  • Open the project with VScode on a Windows machine, delete the Windows directory and execute flutter create. Windows folders will be regenerated (previously you could only manually go to official copy)

  • Flutter is also updated and requires Visual Studio 2019

  • Execute flutter build Windows. After that, you will find the packaged exe under Build/Windows /

Support for copy and paste all these shortcuts, go-flutter can not be used. The only problem is that I find myself pasting with a garble in front of it.

  • Whisper, Flutter for UWP should be coming soon, don’t ask why, I just know.

Flutter for Macos

  • Open the project with vscode on your MAC machine, delete the macos directory and execute flutter create. MAC OS folder will be regenerated, MAC is officially supported on the best desktop, no major issues.

  • Execute flutter build macos. After the build/macos/ folder is installed, the packaged app will be found

  • Here is how to modify the icon and name of app. 1

2. The default app name is Flutter, open runner. Xcodeproj with Xcode and search for product name in Build Settings.

Flutter for Web

  • Open the project with VScode, delete the Web directory and execute flutter Create. The web folder will be regenerated, notice that I have a js reference in index.html to save the Settings

  • Execute flutter build web. After the flutter is complete, the packaged file will be found under Build /web/

Formatting the Dart code

I haven’t done this before. I didn’t format the generated code. I thought you could copy it into the project and format it yourself. But do it, do it beautifully, perfect. Here are a few known formatting methods:

Format the Dart file using a terminal

Dart this is the final call to the terminal to execute the flutter format XXX.dart when doing ff_annotation_route.

Future<void> formatFile(File file) async {
  if (file == null) {
    return;
  }

  if(! file.existsSync()) {print(red.wrap('format error: ${file? .absolute? .path} doesn\'t exist\n'));
    return;
  }

  processRunSync(
    executable: 'flutter',
    arguments: 'format ${file? .absolute? .path}',
    runInShell: true,); }void processRunSync({
  String executable,
  String arguments,
  bool runInShell = false, {})final ProcessResult result = Process.runSync(
    executable,
    arguments.split(' '),
    runInShell: runInShell,
  );
  if(result.exitCode ! =0) {
    throw Exception(result.stderr);
  }
  print('${result.stdout}');
}
Copy the code

Format the Dart file using a network request

Since there is no way to call the terminal when doing UWP, I asked in the group if there is another way. Sure enough, the crowd is awesome, and the cleaning boss has found a way to do dart formatting using web requests. He went after the DartPad, and he was the front man.

Request the address

  • domestichttps://dart-services.dartpad.cn/api/dartservices/v2/format
  • foreignhttps://dart-services.appspot.com/api/dartservices/v2/format
  • Use POST to request JSON{" source ", "dart code"}To return to{" newString "," formatted DART code "}

useDart Style

When I finished writing the DART format of UWP, the cleaning boss lost another link, which can be directly formatted with dart Style.

Two lines of code, that’s easy! It’s nice to have a group of friends.

final DartFormatter formatter = DartFormatter();
result = formatter.format(result);
Copy the code

Making too slow

Recently, I have been using Github too slowly. In fact, I was told a long time ago that I should sync github library to Gitee and then download it from Gitee. I have been lazy and haven’t tried it.

  • Clone the Flutter repository from Github
  • Clone Flutter repository from Gitee

To sign up, just use your Github account

Build a new warehouse

Drag to the bottom to import the existing repository

Enter github’s repository address, for example, flutter

Wait one minute (soon) for the repository to be created

  • Clone to the local PC

  • Sync github repositories. There is a refresh button on the right of the repository name to synchronize github repositories

  • Local change code updated to Github

Terminal type git remote add making https://github.com/flutter/flutter

Git push github

  • In the future, github repositories that are difficult to download must remember to use this method, greatly improving efficiency.

conclusion

Man would not have invented tools if he had not wanted to be lazy. It’s not about making tools, and it’s not about learning more in the process. Welcome to Flutter Candies as a tool maker. (QQ group: 181398081)

And finally, put Flutter Candies on it. It smells sweet.