Be sure to retweet brother for more Flutter posts at ~~~~

Ducafecat WeChat group

B stationhttps://space.bilibili.com/40…

The original

https://medium.com/flutterdev…

code

reference

  • https://pub.dev/packages/json…
  • https://pub.dev/packages/json…

The body of the

Flutter is a portable UI toolkit. In other words, it is a comprehensive application software development kit (SDK), including widgets and tools. Flutter is a free, open source tool for developing mobile, desktop, and Web applications. Flutter is a cross-platform development tool. This means that we can create both iOS and Android applications with the same code. This is the best way to save time and resources throughout the process.

In this article, we’ll explore using the JSON_SERIALIZABLE package and JSON_Annotation, and learn how to use it to parse our model to JSON and generate our own code through serialization. Let’s get started.

JSON Serializable

JSON (JSON) is a data format that encodes objects as strings. This data can be easily converted from server to browser, and from server to server. Serialization is the process of converting an object to the same string. To do this, we use the JSON serialization package, but it can generate a model class for you based on the annotations provided by the JSON annotation library.

Implementation

Whenever we need to build models and factories. Because the model doesn’t always change, you don’t always need to change the model. Therefore, in order to use JSON, we must add some of the packages explained below.

  • This is provided to the Dart build system. When it finds an annotated member in a class defined with JSON_Annotation, it generates code
  • It defines the comments that JSON_SERIALIZABLE uses to create the code for the JSON serialization and deserialization types
  • We use the build_runner package to generate a file that uses the DART code

Now let’s see how to add all of these packages to pubSpec.

  • Step 1: Add dependencies

Add the dependency to the pubspec ー YAML file.

--- dependencies: flutter: sdk: flutter # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS Style ICONS. Cupertino_icons: ^0.1.2 json_annotation: ^4.0.1 dev_dependencies: flutter_test: SDK: flutter build_runner: ^ at 2.0.5 json_serializable: ^ 4.1.3
  • Step 2: Importing
import 'package:json_annotation/json_annotation.dart';
import 'package:build_runner/build_runner.dart';
import 'package:json_serializable/json_serializable.dart';
  • Step 3: Enable AndriodX
org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true

How do I implement the code in a DART file

You need to implement it separately in your code

First, we’ll create a model class that we’ll name User.dart.

Now we’ll see how DART uses the DART: Convert library to natively support manual serialization. So the user dart file is ready, so we’re going to have a list of data JSON objects, where each object is going to have a user name, last name, and its address, and we’ve defined that in a string type variable, and you’ll see that in the data class we have two functions that we need to create, These are called fromJSON and toJSON, respectively, and they convert JSON into our user class.

import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';

@JsonSerializable()
class User {
  String name, lastName, add;
  bool subscription;

  User({this.name,this.lastName,this.add,this.subscription,});

  factory User.fromJson(Map<String,dynamic> data) => _$UserFromJson(data);

  Map<String,dynamic> toJson() => _$UserToJson(this);

}

Now, when we run the build_runner command, json*serializer will generate this *$userfromJSON (json). From this we will get the user.g.art file.

To run the build_runner command, we’ll open a terminal in Android Studio and type the following line.

flutter pub run build_runner build

When we run this command in the build runtime, a few lines appear, and after some time it is successfully generated.

INFO] Generating build script... [INFO] Generating build script completed, took 301ms[INFO] Initializing inputs [INFO] Reading cached asset graph... [INFO] Reading cached asset graph completed, took 305ms[INFO] Checking for updates since last build... [INFO] Checking for updates since last build completed, took 1.5s[INFO] Running build... [INFO] Running build completed, took 4.7s[INFO] Caching dependency graph... Caching dependency graph completed, took 44ms[INFO] Succeeded after 4.8s with 0 outputs (1 Actions)

After the build_runner process is complete, we add a new file named user.g.art below a user file that contains the serialization code. When we make a new model, then we flow through the process.

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'user.dart';

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

User _$UserFromJson(Map<String, dynamic> json) {
  return User(
    name: json['name'] as String,
    lastName: json['lastName'] as String,
    add: json['add'] as String,
    subscription: json['subscription'] as bool,
  );
}

Map<String, dynamic> _$UserToJson(User instance) => <String, dynamic>{
      'name': instance.name,
      'lastName': instance.lastName,
      'add': instance.add,
      'subscription': instance.subscription,
    };

After that, we create a class that displays a list item for which we have defined a future generator list view generator, where we have defined the items for the user list in the text widget.

FutureBuilder<List<User>>(
    future: getData(),
    builder: (context, data) {
      if (data.connectionState != ConnectionState.waiting &&
          data.hasData) {
        var userList = data.data;
        return ListView.builder(
            itemCount: userList.length,
            itemBuilder: (context, index) {
              var userData = userList[index];
              return Container(
                height: 100,
                margin: EdgeInsets.only(top: 30, left: 20, right: 20),
                decoration: BoxDecoration(
                  color: Colors.grey.shade200,
                  borderRadius: BorderRadius.all(Radius.circular(10)),
                ),
                padding: EdgeInsets.all(15),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    Text(
                      'First Name: ' + userData.name,
                      style: TextStyle(
                          fontWeight: FontWeight.w600,),
                    ),
                  ],
                ),
              );
            });
      } else {
        return Center(
          child: CircularProgressIndicator(),
        );
      }
    })

When we run the application, we should get the output of the screen as shown in the screenshot below.

Code File

import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter_json_serilization_exm/main.dart'; import 'package:flutter_json_serilization_exm/model/user.dart'; class JsonSerilization extends StatefulWidget { @override _JsonSerilizationState createState() => _JsonSerilizationState(); } class _JsonSerilizationState extends State<JsonSerilization> { Future<List<User>> getData() async { return await Future.delayed(Duration(seconds: 2), () { List<dynamic> data = jsonDecode(JSON); List<User> users = data.map((data) => User.fromJson(data)).toList(); return users; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Json Serialization Demo"), ), body: Container( child: FutureBuilder<List<User>>( future: getData(), builder: (context, data) { if (data.connectionState ! = ConnectionState.waiting && data.hasData) { var userList = data.data; return ListView.builder( itemCount: userList.length, itemBuilder: (context, index) { var userData = userList[index]; return Container( height: 100, margin: EdgeInsets.only(top: 30, left: 20, right: 20), decoration: BoxDecoration( color: Colors.grey.shade200, borderRadius: BorderRadius.all(Radius.circular(10)), ), padding: EdgeInsets.all(15), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Text( 'First Name: ' + userData.name, style: TextStyle( fontWeight: FontWeight.w600, fontSize: 15), ), Text( 'Last Name: ' + userData.lastName, style: TextStyle( fontWeight: FontWeight.w600, fontSize: 15), ), Text( 'Add: ' + userData.add, style: TextStyle( fontWeight: FontWeight.w600, fontSize: 15), ), ], ), ); }); } else { return Center( child: CircularProgressIndicator(), ); }}),),); }}

Conclusion

In this article, I explained the automatic generation of JSON serialization Flutter, you can modify and experiment according to yourself, this little introduction is a demo from the automatic generation of JSON serialization Flutter from our side.


The elder brother of the © cat

https://ducafecat.tech/

https://github.com/ducafecat

The issue of

Open source

GetX Quick Start

https://github.com/ducafecat/…

News Client

https://github.com/ducafecat/…

Strapi manual translation

https://getstrapi.cn

WeChat discussion group Ducafecat

A series of collections

The translation

https://ducafecat.tech/catego…

The open source project

https://ducafecat.tech/catego…

DART programming language basics

https://space.bilibili.com/40…

Flutter Zero Basics Beginners

https://space.bilibili.com/40…

Flutter combat news client from scratch

https://space.bilibili.com/40…

Flutter component development

https://space.bilibili.com/40…

Flutter Bloc

https://space.bilibili.com/40…

Flutter Getx4

https://space.bilibili.com/40…

Docker Yapi

https://space.bilibili.com/40…