Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Automatic Generate JSON Serializable In Flutter

Flutter is a portable UI toolkit. In other words, it’s a comprehensive app Software Development toolkit (SDK) that comes complete with widgets and tools. Flutter is a free and open-source tool to develop mobile, desktop, web applications. Flutter is a cross-platform development tool. This means that with the same code, we can create both ios and android apps. This is the best way to save time and resources in our entire process.

In this article, we will explore the Automatic Generate JSON Serializable In Flutter using josn_serializable_package and json_annotation, and see how to use it to parse our model into Json and generate our own code by serializing it. so let’s get started.


Table Of Contents :

Generate JSON Serializable

Implementation

Code Implementation

Code File

Conclusion


JSON Serializable:

The JSON (JavaScript Object Notation) is a kind of data format that encodes an object into a string. This kind of data can be easily translated between server and browser, and server to server. Serialization is a process that converts an object into the same string. For this, we use a json_serialization package however it can generate a model class for you as per the annotations provided with the help of the json_annotation library.

Implementation :

Whenever we have to create models and factories. Because models don’t always change so you don’t need to change models all the time. So to use JSON we have to add some of the following packages which are explained below.

  • json_serializable: This is provided to a Dart build system. It generates code when it finds annotated members in a class defined with json_annotation.
  • json_annotation: It defines the annotation used by Json_serializable to create JSON serialization, deserialization type of code.
  • build_runner: We use the build_runner package to generate files using dart code.

Let us now see how we add all these packages to our pubspec.

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:

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.1dev_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 code in dart file :

You need to implement it in your code respectively:

First, we will create a model class of ours which we named user. dart.

Now we will see how manual serialization is done natively supported by Dart with the dart: convert library. User dart file is ready then we will have a list of data JSON objects inside it each object will have a user name, last name, and its address which we have defined in the variable of string type as you will see in the data class we have two We need to create functions called fromJson and toJson which, respectively, translate a JSON to our user.

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, this _$UserFromJson(json) will be generated by json_serializer when we run the build _runner command. From which we will get the user.g.dart file.

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

flutter pub run build_runner build

When we run the command in build runner, some line will appear and after some time it is generated successfully.

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 finished we add a new file named user.g.dart below a user file that contains our serialization code. As we make a new model, then we flow through this 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 we have shown a list item for which we have defined a future builder list view builder inside which we have defined the item of our 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 ought to get the screen’s output like the underneath screen capture.

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 have explained Automatic Generate JSON Serializable In Flutter, which you can modify and experiment with according to your own, this little introduction was from the Automatic Generate JSON Serializable In Flutter demo from our side.

I hope this blog will provide you with sufficient information in Trying up the Automatic Generate JSON Serializable In Flutter in your flutter project. We showed you what the Automatic Generate JSON Serializable In Flutter is and work on it in your flutter applications, So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.

Feel free to connect with us
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.

Leave comment

Your email address will not be published. Required fields are marked with *.