[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-xa5ys5cw-162622190217)( https://ducafecat.tech/2021/07/14/translation/automatic-generate-json-serializable-in-flutter/2021-07-14-08-07-05.png )]
Old iron remember to forward, brother old fellow will show more Flutter good text ~ ~ ~
Wechat group ducafecat
Station b https://space.bilibili.com/404904528
original text
https://medium.com/flutterdevs/automatic-generate-json-serializable-in-flutter-4c9d2d23ed88
code
reference resources
- https://pub.dev/packages/json_serializable
- https://pub.dev/packages/json_annotation
text
Fluent is a portable UI toolkit. In other words, it is a comprehensive application development kit (SDK), including widgets and tools. Fluent is a free open source tool for developing mobile, desktop and web applications. Fluent 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 in the whole process.
In this article, we'll explore using json_serializable packages and json_annotation and learn how to use it to parse our model into JSON and generate our own code through serialization. Let's start.
JSON Serializable
JSON (JSON) is a data format that encodes objects into strings. This data can be easily converted between server and browser, or between server and 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 need to change the model all the time. Therefore, in order to use JSON, we must add some packages explained below.
- This is provided to Dart to build the system. When it's using JSON_ When an annotated member is found in a class defined by annotation, code is generated
- It defines JSON_serializable comments for creating code of JSON serialization and deserialization types
- We use build_ The 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 dart file
You need to implement it separately in your code
First, we'll create a file named user DART's model class.
Now we'll see how dart uses the Dart: convert library to natively support manual serialization. When the user dart file is ready, we will have a list of data JSON objects, in which each object will have a user name, last name and its address. We have defined it in string type variables. You will see that in the data class, we have two functions that we need to create, called fromjason and tojason respectively, 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 build_ When using the runner command, json*serializer will generate this * $UserFromJson(json). We will get user g. Dart file.
To run build_ With the 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 runner, some lines will appear, and after a period of time, it will be 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 finalized dependency graph...[INFO] Caching finalized dependency graph completed, took 44ms[INFO] Succeeded after 4.8s with 0 outputs (1 actions)
In build_ After the runner process is completed, we add a user named user under a user file that contains the serialization code g. New file for dart. 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 created a class that displays a list item for which we have defined a future generator list view generator, where 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.
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (IMG mylnnjbj-162622190218)( https://ducafecat.tech/2021/07/14/translation/automatic-generate-json-serializable-in-flutter/2021-07-14-07-56-13.png )]
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 serialized Flutter. You can modify and experiment according to yourself. This small introduction is from the demonstration of automatic generation of JSON serialized Flutter from our side.
© Cat brother
https://ducafecat.tech/
https://github.com/ducafecat
Previous period
Open Source
GetX Quick Start
https://github.com/ducafecat/getx_quick_start
News client
https://github.com/ducafecat/flutter_learn_news
Translation of strapi manual
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/
Basics of Dart programming language
https://space.bilibili.com/404904528/channel/detail?cid=111585
Introduction to Flutter zero Foundation
https://space.bilibili.com/404904528/channel/detail?cid=123470
Flutter actual combat news client from scratch
https://space.bilibili.com/404904528/channel/detail?cid=106755
Fluent 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