Working with JSON in Flutter While Using json_annotations and json_serializable Modules in 2022
--
How to use Flutter/Dart’s magical ways to convert JSON data into usable structures so that you can get unstuck — and get going.
Why are you here?
You have read tons of Medium posts and watched plenty of YouTube videos and still feel a little confused. Along the way, you found various ways to convert JSON into Dart code magically. But … it doesn’t work quite right.
Let’s do this
Follow along in 5-ish steps:
- Add three modules to your project from the command-line:
unix% flutter pub add json_serializable
unix% flutter pub add json_annotation
unix% flutter pub add build_runner
and then adjust your pubspec.yaml
file by moving two of the entries underneath dev_dependencies
to look like so:
2. Any place you intend to use this module you’ll need this header for your file (let’s say the file’s named special.dart
):
import 'package:json_annotation/json_annotation.dart';
3. Your special.dart file needs a line of code that reads:
part 'special.g.dart'
Note that weird “.g” you need to add — be sure to match this statement with your actual file name. You’ll thank me later.
4. Each time you define a class manually with data inside it, it should have the format:
@JsonSerializable()class Person {// required vs optional distinction gets made by whether
// you say it's nullable? or not / you'll need to match it
// up with what you stick in your constructor / required
// means it's necessary; and if it's optional, you need
// to nullable? the instance variable explicitly