Serialization Of Objects In Flutter
Almost every mobile application in the market today has a feature to fetch data from the internet or store the user’s data in the mobile local storage. The data that we get from the internet from an API is not in a readable language or we can say that it can be understood by the application. The data thrown by the application is in JSON format so it is important to convert the JSON data. So we can display it to the users. JSON stands for JavaScript Object Notation.
Flutter uses dart:convert
library to convert the JSON data. This library provides us decoder the encode and decode the JSON data.
To use these decoders we need to import it:
import 'dart:convert';
The data that we will receive in JSON format will be in a sequential manner. It will contain similar data multiple times. So now we need to create an object to use it. To create an object we need to make or define its blueprint i.e. we need to create a model class.
Creating a Model class for an Object:
We have created a Fruit class model that contains id
, title
, imageUrl
, quantity
,also define the constructor for the class.
class Fruit {
final int id;
final String title;
final String imageUrl;
final int quantity;
//constructor
Fruit(
this.id,
this.title,
this.imageUrl,
this.quantity,
);
}
This is the base model of the data that we are going the receive from our API in JSON format. So need to convert the JSON data with our Fruit.
class Fruit {
final int id;
final String title;
final String imageUrl;
final int quantity;
Fruit(
this.id,
this.title,
this.imageUrl,
this.quantity,
);
factory Fruit.fromJson(Map<String, dynamic> json) {
return Fruit(json['id'], json['name'], json['image_url'], json['quantity']);
}
Map<String, dynamic> toJson() => {
'id' : id,
'title' : title,
'imageUrl' : imageUrl,
'quantity' : quantity
};
}
What is dynamic?
It is a keyword that we use to get unknown data. The API data that we get is not typically defined that is why dynamic is used so that whatever the data type data we get we can convert it into its datatype only if the data is a string it will be of type int. It is used when no type is declared for data.
What is factory?
It returns an instance of a class. Dart provides factory
keyword to label a default or named constructor. Then it becomes our responsibility to return an instance from this constructor. A factor constructor is generally used to control the instance creation.
- fromJson method converts the JSON data and returns a Fruit object that contains the data that came in JSON data.
- toJson method converts the data into JSON format.
Serialize and De-Serialize Data:
Let’s assume using fromJson we get a dummy Fruit object:
Fruit fruit = Fruit(1, "title", "imageUrl", 23);
Now to convert it into JSON data we use the jsonEnode()
method or json.encode()
.
String toJSONFruit = jsonEncode(fruit);
Decoding Fruit:
String fromJSONFruit = jsonDecode(fruit);
Converting the decoded Fruit to Fruit object:
Fruit deCodedFruit = new Fruit(
fromJSONFruit['id'],
fromJSONFruit['name'],
fromJSONFruit['image_url'],
fromJSONFruit['quantity']);
Multiple object Serialization:
final parsed = json.decode(jsonData).cast<Map<String, dynamic>>();
return parsed.map<Fruit>((json) => Fruit.fromMap(json)).toList();
parsed
variable contains all the JSON data and using the map function we can map each Fruit JSON data to a Fruit object.
you can also use fromMap
function to map the JSON data or you can directly map each data with Fruit attribute like deCodedFruit
.
factory Fruit.fromMap(Map<String, dynamic> json) {
return Fruit(
json['number'], json['name'], json['image_url'], json['status']);
}
Complete example:
flutter-devs/rest_API_demo
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com
🌸🌼🌸 Thank you for reading. 🌸🌼🌸🌼
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 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!.