Model codegen using build_value package in Flutter

Artem Diashkin
Apr 25, 2020 · 4 min read

How to generate Model classes on a fly for complex data structure? Let’s find out.

Problems

First, let’s talk about few problems that you could catch as a developer, while creating/updating/deleting properties from your model classes.

If you have a simple JSON object model like this:

{
"by" : "dhouston",
"descendants" : 71,
"id" : 8863,
"kids" : [ 9224, 8917, 8952 ],
"score" : 104,
"time" : 1175714200,
"title" : "My YC app: Dropbox - Throw away your USB drive",
"type" : "story",
"url" : "http://www.getdropbox.com/u/2/screencast.html"
}

https://hacker-news.firebaseio.com/v0/item/8863.json?print=pretty

And you need to create a new Object() from this data after fetching, you would probably create a new class with a custom name, like Item , with some properties:

That’s fine. But for converting JSON data to an object we should add some method that will convert JSON data to a Dart object, like this:

Item parseItem(String jsonStr) {
final parsed = json.decode(jsonStr);
return Item.fromJson(parsed);
}

… and to test that in our json_test.dart:

const jsonString =
'{"by":"dhouston","descendants":71,"id":8863,"kids":[8872,8876],"score":104,"time":1175714200,"title":"My YC app: Dropbox - Throw away your USB drive","type":"story","url":"http://www.getdropbox.com/u/2/screencast.html"}';
void main() {
test("parses item json data", () {
expect(parseItem(jsonString).by, 'dhouston');
});
}

Ok. But for proper work with Dart models, our object properties should be private, with getters and setters, with overriding hashCode and equal operator. And after all, that changes our “simple” class to this:

And what if you got like tons of such classes, with other classes as properties that are in the collection of other classes that have Enums/String/Ints Dates, and so on and so forth.

https://www.reddit.com/r/popular/new.json?count=25

It will become a pain in the ass… real headache to maintain changes in such Model structure.

There is a great solution to solve that — build_value

At first, we will need to add few packages to our project:

  • built_value
  • built_collection
  • built_value_generator
  • build_runner
dependencies:
...
built_value: ^7.1.0
built_collection: ^4.3.2
dev_dependencies:
built_value_generator: ^7.1.0
build_runner: ^1.9.0

After installing those packages we will need to describe that “complex” data structure to code generator:

To simplify “describing” you can use code snippet plugin in your IDE.

Let’s take a quick look on how it works in Android Studio:

Step 1

In a someName.dart file

import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
import 'package:built_collection/built_collection.dart';

part 'someName.g.dart';

Create an abstract class using code snippet:

Here, we are telling generator that we want to generate a class SomeClassName with String property someValue .

Step 2

Run this command in ROOT path of your project:

flutter packages pub run build_runner watch

watch means that each time you will update properties in classes in your someName.dart file it will automatically re-generate all previously generated code.

After running this command someName.g.dart file will be generated with this data in it:

Back to business

Now, when you know how it work, let’s get back to explaining previous “complex” code fragment:

After running …

flutter packages pub run build_runner watch

… you will get a whole bunch of stuff in your generated file:

Generating serializers

Next, we need to generate serializers. The process is mostly the same.

  1. Describe what you what to generate. You can use a code snippet for that too:

2. Run the command

flutter packages pub run build_runner watch

Or, if you ran this command previously with watch flag, just save your changes and build_runner will automatically detect changes and will re-run the script.

Let’s test it

Create a function that will fetch Reddit data and parse it:

And in some test file:

Let’s see what our function will return:

P.S. Building new object

Because your classes are immutable you can create you new object like this:

new Post((b) => b
..author = 'yashsaini9127'
..url = 'https://some-url'
..title = 'What will you choose'
..ups = 1);

And that’s it!

You can add/update/delete properties from your classes and build_runner will automatically re-generate it on a fly 👍

LITSLINK

LITSLINK’s team is sharing their experience

Sign up for LITSLINK Newsletter

By LITSLINK

It's a test newsletter! Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Artem Diashkin

Written by

Java, Spring, Node.js, AdonisJs, React.js and Flutter developer

LITSLINK

LITSLINK

Hands-on up to date experience sharing of the most skilled & talented software developers right here, right now. Subscribe to learn & understand more about the Software World.

Artem Diashkin

Written by

Java, Spring, Node.js, AdonisJs, React.js and Flutter developer

LITSLINK

LITSLINK

Hands-on up to date experience sharing of the most skilled & talented software developers right here, right now. Subscribe to learn & understand more about the Software World.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store