0
0
FlutterHow-ToBeginner · 3 min read

How to Create Model from JSON in Flutter: Simple Guide

To create a model from JSON in Flutter, define a Dart class with fields matching the JSON keys and add a factory constructor named fromJson that converts a Map<String, dynamic> to the model object. Use jsonDecode from dart:convert to parse JSON strings into maps, then call Model.fromJson to create the model instance.
📐

Syntax

Define a Dart class with fields matching your JSON structure. Add a factory constructor named fromJson that takes a Map<String, dynamic> and returns an instance of the class. Use jsonDecode to convert a JSON string into a map.

  • class Model: Your data model class.
  • factory Model.fromJson(Map<String, dynamic> json): Creates an instance from JSON map.
  • jsonDecode(String jsonString): Parses JSON string to map.
dart
import 'dart:convert';

class Model {
  final String field1;
  final int field2;

  Model({required this.field1, required this.field2});

  factory Model.fromJson(Map<String, dynamic> json) {
    return Model(
      field1: json['field1'],
      field2: json['field2'],
    );
  }
}

void main() {
  String jsonString = '{"field1": "value", "field2": 123}';
  Map<String, dynamic> userMap = jsonDecode(jsonString);
  Model model = Model.fromJson(userMap);
  print('field1: ${model.field1}, field2: ${model.field2}');
}
Output
field1: value, field2: 123
💻

Example

This example shows how to create a User model from a JSON string. It parses the JSON, creates the model, and prints the user's name and age.

dart
import 'dart:convert';

class User {
  final String name;
  final int age;

  User({required this.name, required this.age});

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      name: json['name'],
      age: json['age'],
    );
  }
}

void main() {
  String jsonString = '{"name": "Alice", "age": 30}';
  Map<String, dynamic> userMap = jsonDecode(jsonString);
  User user = User.fromJson(userMap);
  print('Name: ${user.name}, Age: ${user.age}');
}
Output
Name: Alice, Age: 30
⚠️

Common Pitfalls

Common mistakes when creating models from JSON include:

  • Not matching JSON keys exactly with model fields.
  • Forgetting to handle null or missing fields.
  • Using wrong data types (e.g., expecting int but JSON has string).
  • Not importing dart:convert for jsonDecode.

Always check your JSON structure and handle optional fields safely.

dart
import 'dart:convert';

class Product {
  final String name;
  final double price;

  Product({required this.name, required this.price});

  // Wrong: missing factory constructor
  // Product.fromJson(Map<String, dynamic> json) {
  //   name = json['name'];
  //   price = json['price'];
  // }

  // Correct way:
  factory Product.fromJson(Map<String, dynamic> json) {
    return Product(
      name: json['name'],
      price: (json['price'] as num).toDouble(),
    );
  }
}

void main() {
  String jsonString = '{"name": "Book", "price": 9.99}';
  Map<String, dynamic> productMap = jsonDecode(jsonString);
  Product product = Product.fromJson(productMap);
  print('Product: ${product.name}, Price: ${product.price}');
}
Output
Product: Book, Price: 9.99
📊

Quick Reference

Tips for creating models from JSON in Flutter:

  • Use factory constructors named fromJson for parsing.
  • Use jsonDecode to convert JSON strings to maps.
  • Match your Dart fields to JSON keys exactly.
  • Handle nullable or missing fields with care.
  • Convert numeric types safely (e.g., num to double).

Key Takeaways

Define a Dart class with fields matching your JSON structure.
Use a factory constructor named fromJson to parse JSON maps into model objects.
Use jsonDecode from dart:convert to convert JSON strings to maps before parsing.
Always handle null or missing fields to avoid runtime errors.
Match data types carefully, converting numbers as needed.