📒
Mobile Development Reference-TCE-C01
  • Welcome
  • Introduction
    • Project Description
  • First Steps
    • Creating Project
    • Setting up Workspace
      • Project structure
      • Setting up the app
  • Routing
    • Setting up auto route
    • Creating the first screen
    • Setting up router
    • Adding router to Material App
  • Products Feature
    • Creating models
      • Introduction to freezed
      • Introduction to JSON annotations
      • Creating products model
    • Creating products cubit
      • Creating Products States
      • Creating Products Cubit
      • Implementing Get Products Functionality
    • Creating products repository
      • Setting up Dio
      • Making your first http request with DIO
    • Implementing Products Screen UI
      • Adding Products Grid
      • Adding Products Tile
      • Add Products Error Widget
    • Consuming the products cubit
      • Setting up Dependency injection
      • Creating Bloc Provider for ProductsCubit
      • Mapping Products Cubit states to UI
  • Testing
    • Widget Testing
    • Unit Testing
Powered by GitBook
On this page

Was this helpful?

Export as PDF
  1. Products Feature
  2. Creating models

Introduction to JSON annotations

Installing and Using json_serializable and json_annotation packages

Add this to your package's pubspec.yaml file:

# pubspec.yaml
dependencies:
  json_annotation: ^4.0.0

dev_dependencies:
  build_runner:
  json_serializable 4.0.2

You can then install packages from the command line:

$ dart pub get

Alternatively, your editor might support dart pub get. Check the docs for your editor to learn more.

Example

Now you can use it in your Dart code by importing it like this:

import 'package:json_annotation/json_annotation.dart';

part 'my_model.g.dart';

Note that the line partmy_demo.g.dartwill give you a warning, because the file is not created yet

Write the following code

import 'package:json_annotation/json_annotation.dart';

part 'my_model.g.dart';

@freezed
class Person with _$Person {
  const factory Person({
    @required String firstName,
    @required String lastName,
  }) = _Person;

  factory Person.fromJson(Map<String, dynamic> json) =>
      _$PersonFromJson(json);
}

To generate the code type the following command

$ flutter pub run build_runner build

Ignore lint warnings on generated files

It is likely that the code generated by Json_Serializer will cause your linter to report warnings.

The solution to this problem is to tell the linter to ignore generated files, by modifying your analysis_options.yaml:

analyzer:
  exclude:
    - "**/*.g.dart"

PreviousIntroduction to freezedNextCreating products model

Last updated 4 years ago

Was this helpful?