Old iron remember to forward, Brother Mao will present more Flutter good articles~~~~

WeChat group ducafecat

b Station https://space.bilibili.com/404904528

original

https://medium.com/flutterdevs/automatic-generate-json-serializable-in-flutter-4c9d2d23ed88

Code

reference

text

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 and open source tool for developing mobile, desktop and web applications. Flutter is a cross-platform development tool. This means that with the same code, we can create ios and android applications at the same time. This is the best way to save time and resources throughout the process.

In this article, we will explore the use of the json_serializable package and json_annotation, and learn how to use it to parse our model into JSON and generate our own code through serialization. let us start.

JSON Serializable

JSON (JSON) is a data format that encodes objects into strings. This kind of data can be easily converted between the server and the browser, and can also be converted between the server and the server. Serialization is the process of converting objects into the same string. For 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 does not always change, you don't need to always change the model. Therefore, in order to use JSON, we have to add some 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 will generate code
  • It defines the comment of JSON_serializable to create the code of JSON serialization and deserialization type
  • We use the build_runner package to generate files using dart code

Now let's see how to add all these packages to pubspec.

  • Step 1: add dependencies
Add dependencies 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: ^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 to implement the code in the dart file

You need to implement it in your code separately

First, we will create a model class that we named user.dart.

Now we will see how Dart uses the Dart: convert library to natively support manual serialization. The user dart file is ready, we will have a list of data JSON objects, each of which will have a user name, last name, and its address, we have defined it in a string type variable, you will see In the data class, we have two functions that we need to create, called fromJson and toJson, which 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) . We will get the user.g.dart file from it.

To run the build_runner command, we will open a terminal in Android Studio and enter the following line.

flutter pub run build_runner build

When we run this command in the build and run program, some lines will appear, and it will be successfully generated after a period of time.

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 finalized
dependency graph...[INFO] Caching finalized dependency graph completed, took 44ms[INFO] Succeeded after 4.8s with 0 outputs (1 actions)

After the build_runner process is completed, we add a new file named user.g.dart under a user file containing 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 this, we have created a class in which a list item is displayed, and we have defined a future generator list view generator for this list item, in which we have defined the items of 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, just like 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 your own, this small introduction is from the automatic generation of JSON serialization Flutter demonstration from our side.


© Cat brother

https://ducafecat.tech/

https://github.com/ducafecat

Past

Open source

GetX Quick Start

https://github.com/ducafecat/getx_quick_start

News client

https://github.com/ducafecat/flutter_learn_news

strapi manual translation

https://getstrapi.cn

WeChat discussion group ducafecat

Series collection

Translation

https://ducafecat.tech/categories/%E8%AF%91%E6%96%87/

Open source project

https://ducafecat.tech/categories/%E5%BC%80%E6%BA%90/

Dart programming language basics

https://space.bilibili.com/404904528/channel/detail?cid=111585

Getting started with Flutter zero foundation

https://space.bilibili.com/404904528/channel/detail?cid=123470

Flutter actual combat from scratch news client

https://space.bilibili.com/404904528/channel/detail?cid=106755

Flutter component development

https://space.bilibili.com/404904528/channel/detail?cid=144262

Flutter Bloc

https://space.bilibili.com/404904528/channel/detail?cid=177519

Flutter Getx4

https://space.bilibili.com/404904528/channel/detail?cid=177514

Docker Yapi

https://space.bilibili.com/404904528/channel/detail?cid=130578


独立开发者_猫哥
666 声望126 粉丝