Skip to main content

Command Palette

Search for a command to run...

Save Time. Avoid Errors. Use Trusted Serialization Tools in Flutter!

Updated
5 min read
Save Time. Avoid Errors. Use Trusted Serialization Tools in Flutter!
R

I'm Renga, a Flutter developer passionate about building efficient and scalable apps. I share whatever I learn with the world every weekend, covering insights, best practices, and real-world solutions to help developers master Flutter. Let’s learn and build together!

Initially, I wrote most of the serialization code by myself. To be frank, sometimes I made some mistakes that consumed more time to fix, so, indirectly, it affected my delivery time. That time I found this awesome way to save my time in a smarter way. Now I’m going to share the secret masala with you, my people.

What will you gain from this blog?

  • JSON serialization and deserialization by using trusted packages to reduce our time.

  • Nested serialization flow.

  • Pro techniques in package.

  • I added my Git repo for you to understand more clearly and Hanson as well.


Step 1: Add required packages.

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.8
  json_annotation: ^4.9.0 // 1

dev_dependencies:
  flutter_test:
    sdk: flutter
  json_serializable: ^6.9.4 // 2
  build_runner: ^2.4.15 // 3
  flutter_lints: ^5.0.0

Step 2: Create Base Model

//* Jsut for referance
{
  "userId": "u123",
  "name": "Renga",
  "joinedAt": "2024-10-12T10:00:00Z",
  "optionalBio": "Flutter Dev",
  "isActive": true,
  "address": {
    "street": "123 Main St",
    "city": "Chennai"
  },
  "role": "admin"
}
  • Create a “user.dart“ under the lib folder.

  • First, analyze the JSON. Like, what are the properties? What are all the nested models? And based on the JSON string, we are going to create a model along with a constructor.

  • As per the given JSON string, we need to create 2 model files. One is user, and another one is address.

  • Here I will teach you how to write code for user mode. Next, try to write by yourself for address mode and add it into the user model.

class User {
  final String userId;
  final String? name;
  final DateTime? joinedAt;
  final String? optionalBio;
  final bool isActive;
  final Address address;
  final String role;
  User({
    required this.userId,
    this.name,
    this.joinedAt,
    this.optionalBio,
    required this.isActive,
    required this.address,
    required this.role,
  });

Notes:

  • The class property name and JSON key value should be the same. (its not case sensitive.)

    • If the JSON key is “userId”, the class property should be “userId.”

    • If the JSON key is “user_id“, the class property should not be “userId“. It should be “user_id“. (We can change the property name; i will tell you later. First, fiesrt we focus on basics.)

  • The class property should be nullable when the JSON property should be nullable. Otherwise we will get an error.


Step 3: Add Required lines

import 'package:json_annotation/json_annotation.dart'; //* required (1)
import 'package:serilazation/model/example2/address.dart';

part 'user.g.dart'; //* required (2)

@JsonSerializable() //* required (3)
class User {
  final String userId;
  final String? name;
  final DateTime? joinedAt;
  final String? optionalBio;
  final bool isActive;
  final Address address;
  final String role;
  User({
    required this.userId,
    this.name,
    this.joinedAt,
    this.optionalBio,
    required this.isActive,
    required this.address,
    required this.role,
  });

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json); //* required (4)
  Map<String, dynamic> toJson() => _$UserToJson(this); //* required (5)
}

Note 1: (part) line - required (2)

part '[FILE_NAME].g.dart';
  • Here, part 'user.g.dart';have a user word. It should be a file name. Otherwise, you will get an error.

  • This isabcd.g.dart automatically generated by the system (after running the command). I will share it later.

  • This file contains the serialization logic.

  • This line helps to add that auto-generated file into our file.

Note 2: (JsonSerializable) line - required (1), required (3)

@JsonSerializable()
  • We are telling the dart that this is the model for your reference to create serialization logic.

  • Sometimes, you will get an error once you add the @JsonSerializable()line. That time, just import the json_annotationpackage. After that you won’t get any errors.

  • Here, at the end of the line, there is no semicolon that will come.

  • If you missed this line, system will generate the abcd.g.dart file; but still you getting the error in serialization functions (4, 5)

Note 3: (fromJson, toJson) line - required (4), required (5)

factory [CLASS_NAME].fromJson(Map<String, dynamic> json) => _$[CLASS_NAME]FromJson(json);
Map<String, dynamic> toJson() => _$[CLASS_NAME]ToJson(this);
  • Here, the class name will come to create aformJson named constructor.

  • The first letter should be uppercase in both places.

  • If you give as small case, you will get error on the callback functions


Step 4: Run the command

  • This is the important part. Once you set up everything, run the below code in your terminal.
dart run build_runner build --delete-conflicting-outputs
  • —delete-conflicting-outputsThe flag helps us to remove existing files.

  • Once you run the command, the system will generate the abcd.g.dartfile for each model file.

  • If the respective abcd.g.dartfiles are created, we have completed 75% of the work.


Step 5: Adding mocked JSON string

//* step:1
String mockedUserJson = ```
{
  "user_id": "u123",
  "name": "Renga",
  "joined_at": "2024-10-12T10:00:00Z",
  "optionalBio": "Flutter Dev",
  "isActive": true,
  "address": {
    "street": "123 Main St",
    "city": "Chennai"
  },
  "role": "admin"
}
```;

//* step2: create instance
late User user;

//* step3: JSON to object
user = User.fromJson(jsonDecode(user));
print(user.name);

//* step4: object to JSON
var jsonUser = jsonEncode(user.toJson());
print(jsonUser);
  • Add the above mock data and run it yourself.


note:

I will teach you the PRO techniques and tips in the next blog. We will meet next blog see you my people.

Happy coding!