DEV Community

Edu Deza
Edu Deza

Posted on

Improve your Flutter network requests

One of the most important goals making mobile requests is reduce as much as possible the size and time.

If you've read the article JSON and serialization and you are using the library json_serializable it's very easy to serialize nested objects.

But we have a trouble with serialization of these nested objects.

See an example, so suppose you have these two classes:


@JsonSerializable(explicitToJson: true)
class Brand {
 int id;
 String name;

 Brand(this.id, this.name)

 factory Brand.fromJson(Map<String, dynamic> json) => 
 _$BrandFromJson(json);

  Map<String, dynamic> toJson() => _$BrandToJson(this);
}

@JsonSerializable(explicitToJson: true)
class Car {
 int id;
 String model;
 String fuel;
 Brand brand;

 Car(this.name, this.fuel, this.brand)

 factory Car.fromJson(Map<String, dynamic> json) => 
 _$CarFromJson(json);

  Map<String, dynamic> toJson() => _$CarToJson(this);
}
Enter fullscreen mode Exit fullscreen mode

As you can see, Car has a relation to Brand. So, if you do:

Brand brand = Brand(1, "Ford");
Car car = Car("Mustang", "gasoline", brand);

print(car.toJson());
Enter fullscreen mode Exit fullscreen mode

The result is:

{name: Mustang, fuel: gasoline, brand: {id: 1, name:ford}}
Enter fullscreen mode Exit fullscreen mode

Every time you do a request you are sending the above payload.

Ok, in this case it's not a problem because is small, but if we have a complex objects modeling, this may be a problem serializing all brand properties.

So we can do a simple but a great improvement adding a @JsonKey (json_annotation package).

@JsonSerializable(explicitToJson: true)
class Car {
 int id;
 String model;
 String fuel;

 @JsonKey(toJson: _brandJsonReplace)
 Brand brand;

 static Map<String, int> _brandJsonReplace(Brand brand) => {"id": brand.id};

 Car(this.name, this.fuel, this.brand)

 factory Car.fromJson(Map<String, dynamic> json) => 
 _$CarFromJson(json);

  Map<String, dynamic> toJson() => _$CarToJson(this);
}
Enter fullscreen mode Exit fullscreen mode

Now following the previous example:

Brand brand = Brand(1, "Ford");
Car car = Car("Mustang", "gasoline", brand);

print(car.toJson());
Enter fullscreen mode Exit fullscreen mode

The result is:

{name: Mustang, fuel: gasoline, brand: {id: 1}}
Enter fullscreen mode Exit fullscreen mode

As you can see, brand properties are replaced by only id property, reducing payload size.

Ok, it's not a perfect solution and of course depends on your object relationships. But I think it's a simple and effective way to improve the requests.

Top comments (0)