Introduction To Built_Value Library In Dart

This post is an introduction to built_value library in Dart. We will go over what problem this library is solving in Dart and Flutter applications.

Introduction

Although Dart is an excellent programming language, the dart classes and enums aren’t very much efficient. They suffer from quite a few drawbacks like serialization, immutability and object comparison.

Serialization Problem In Dart

In any app, we quickly face the need to serialize our data models. Maybe we want to convert them into JSON objects or into stream of bytes or transmit them to memory or a database. Dart doesn’t have default support for serialization/de-serialization of objects.

JSON Serialization In Dart

Let’s say we have a model called Divison.

In order to serialize this model into JSON in dart, we would need to write quite a lot of extra code.

First, we will have to write code to convert it into a JSON object.

Then, again write some more code to convert the JSON back to dart object.

Imagine having to do the for each of your model objects!

Immutability In Dart

In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created. We want our data models to be immutable so that any change made to the object can be reflected anywhere throughout an app.

For example, in an e-commerce app we want the items in a cart to be updated consistently through out the app. Immutability guarantees that all such local changes are in sync.

Dart doesn’t support this kind of immutability.

Object Comparison In Dart

Dart objects are reference types and not value types. Therefore, object comparison is difficult.

Become A Flutter Expert With This Course

For example:

Although we would expect person1 and person2 be the same person, Dart wouldn’t agree.

Since, these objects are not value types, Dart treats them as different objects.

Enter Built_Value Library In Dart

Wall Built With Stones
Just A Wall Built With Stones

Built Value (built_value) library was specifically created to solve the problems that we saw earlier with Dart. It provides full support for Serialization, Immutability and Object Comparison in a Dart/Flutter application. We can build our own value types using this library.

Besides solving the problems mentioned above, built_value library comes with more valuable features like:

  • pre-condition checks like null checks,
  • support for hash value generation,
  • converting objects to String,
  • complex data Serialization,
  • and much more!

Conclusion

In this post, we learnt about why we need the built_value library in dart and flutter applications. The main problems this library solves were explained with examples. In the coming posts, we will learn more about implementing the built_value library in a Flutter application.

Learn More About Built_Value

About the author