Flutter HTTP package

The http package provides the simplest way to fetch data from the internet.

To install the http package, add it to the dependencies section of the pubspec.yaml. You can find the latest version of the http package on the Pub site. Then just run flutter pub get in terminal section of Android Studio. now we want to serialize to/from our Flutter models like we do in c# and it is easy !

Serializing JSON inside model classes

I will be using  plain model class, called User in this example. Inside the User class, you’ll find:

  • User.fromJson() constructor, for constructing a new User instance from a map structure.
  • toJson() method, which converts a User instance into a map.
class User{ 
String id;  
String email; 
String password;  
User.fromJson(Map<String, dynamic> json): 
       id = json['id'], email =json["email"], password = json['password']; 
Map<String, dynamic> toJson() => {     'id': id,    'email': email,    'password' :password  };

The responsibility of the decoding logic is now moved inside the model itself. With this new approach, you can decode a user easily. NOTE:jsonstring was delivered in the payload of an Http Post

Map userMap = jsonDecode(jsonString); 
var user = User.fromJson(userMap);

To encode a user, pass the User object to the jsonEncode() function. You don’t need to call the toJson() method, since jsonEncode() already does it for you.

String json = jsonEncode(user);

With this approach, the calling code doesn’t have to worry about JSON serialization at all. 

But gee, I had to write some ugly code in User.fromJson and this is not bad in this simple example but in most cases our model has many more properties and there might be nested classes which I will deal with later. So to the rescue , there is  automated source code generator that generates the JSON serialization boilerplate for you. Just add the following code to the top of user.dart:

import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';

/// An annotation for the code generator to know that this class needs the
/// JSON serialization logic to be generated when we do the flutter pub run build_runner build

Note: user.g.dart will be undefined till we complete the code generation step as this is the class that is produced.

Then we modify the fromJson and toJson constructors to use methods on the user.g.dartso the class looks like:


class User{
  String id;
  String email;
  String password;


  /// A necessary factory constructor for creating a new User instance
  /// from a map. Pass the map to the generated `_$UserFromJson()` constructor.
  /// The constructor is named after the source class, in this case, User.
  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);

  /// `toJson` is the convention for a class to declare support for serialization
  /// to JSON. The implementation simply calls the private, generated
  /// helper method `_$UserToJson`.
  Map<String, dynamic> toJson() => _$UserToJson(this);

to invoke the code generator we issue:

flutter pub run build_runner build

This will produce the serialization code we need in user.g.dart:

part of 'user.dart'; //JsonSerializableGenerator//
User _$UserFromJson(Map<String, dynamic> json) {
   return User( id: json['id'] as String,
      email: json['email'] as String, 
      password: json['password'] as String);  
 Map<String, dynamic> _$UserToJson(User instance) => <String, dynamic>{       
   'id': instance.id,   
    'email': instance.email, 
    'password': instance.password   

Leave a reply:

Your email address will not be published.

Site Footer

Sliding Sidebar