0
0
Fluttermobile~5 mins

Model classes from JSON in Flutter

Choose your learning style9 modes available
Introduction

Model classes help you organize data from JSON into easy-to-use objects in your app.

When you get data from a web service in JSON format.
When you want to convert JSON data into Dart objects to use in your app.
When you want to send data from your app as JSON to a server.
When you want to keep your code clean and easy to understand by using classes.
When you want to avoid working with raw JSON maps everywhere in your code.
Syntax
Flutter
class ModelName {
  final Type propertyName;

  ModelName({required this.propertyName});

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

  Map<String, dynamic> toJson() {
    return {
      'propertyName': propertyName,
    };
  }
}

The fromJson factory converts JSON map to a Dart object.

The toJson method converts the Dart object back to JSON map.

Examples
This model class represents a user with a name and age.
Flutter
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'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'name': name,
      'age': age,
    };
  }
}
This model class shows how to handle numbers that might be int or double in JSON.
Flutter
class Product {
  final String id;
  final double price;

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

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

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'price': price,
    };
  }
}
Sample App

This Flutter app shows how to convert a JSON string into a User object and display its data on screen.

Flutter
import 'dart:convert';
import 'package:flutter/material.dart';

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'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'name': name,
      'age': age,
    };
  }
}

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    const jsonString = '{"name": "Alice", "age": 30}';
    final Map<String, dynamic> userMap = json.decode(jsonString);
    final user = User.fromJson(userMap);

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('User Info')),
        body: Center(
          child: Text('Name: ${user.name}, Age: ${user.age}'),
        ),
      ),
    );
  }
}
OutputSuccess
Important Notes

Always check JSON keys exist before using them to avoid errors.

Use toDouble() when JSON numbers can be int or double.

Model classes make your code easier to maintain and test.

Summary

Model classes convert JSON data into Dart objects and back.

Use fromJson factory and toJson method.

This helps keep your app code clean and organized.