Flutter. Model codegen using build_value package.

Problems

{
"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"
}
Item parseItem(String jsonStr) {
final parsed = json.decode(jsonStr);
return Item.fromJson(parsed);
}
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');
});
}
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

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

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

Step 1

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

part 'someName.g.dart';

Step 2

flutter packages pub run build_runner watch

Back to business

flutter packages pub run build_runner watch

Generating serializers

flutter packages pub run build_runner watch

Let’s test it

P.S. Building new object

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

And that’s it!

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

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