Flutter

Flutter – How to Create Dart Object from JSON

In this post, we will understand the concepts in relation to creating a Dart object from a JSON object and how to use these DART objects in Flutter app. We will build an app and run the code shown in this post. 

Here is an example JSON object which we will work with, in order to create a custom Dart object called as School. The JSON represents information about a school including name, address, departments. You may note that the JSON object is primarily of type Map<String, dynamic> where key is String and value is of dynamic type. The key, name, is of type <String, String>, the key, address, is of type <String, Object> and the key, departments is of type <String, List<Object>>

 

{
    "name": "IIT Kharagpur",
    "address": {"city": "Kharagpur", "state": "West Bengal"},
    "departments": [
      {"name": "Computer Science",
        "seats": 50
      },
      {"name": "Electronics",
        "seats": 70
      },
      {"name": "Electrical",
        "seats": 80
      },
      {"name": "Mechanical",
        "seats": 100
      },
    ]
  }

In order to read above object, we will need to create a DART representation of School. School class will be composed of an Address and List of Department objects. Take a look at the following code. It comprises of three classes.

  • School class which comprises of three member variables such as name, address and list of departments
  • Address class
  • Department class

Each of the classes have static or factory method to create the respective DART object from JSON object

// School Object
class School {

  String name;
  Address address;
  List<Department> departments;

  School({
    this.name,
    this.address,
    this.departments
  });

  static fromJson(Map<String, dynamic> parsedJson){
    return School(
        name: parsedJson['name'],
        address : Address.fromJson(parsedJson['address']),
        departments : Department.listFromJson(parsedJson['departments'])
    );
  }
}
//
// Department object
//
class Department {
  String name;
  int seats;

  Department({
    this.name,
    this.seats
  });

  static listFromJson(List<Map<String, dynamic>> list) {
    List<Department> departments = [];
    for (var value in list) {
      departments.add(Department.fromJson(value));
    }
    return departments;
  }

  static fromJson(Map<String, dynamic> parsedJson){
    return Department(
        name: parsedJson["name"],
        seats: parsedJson["seats"]
    );
  }

}
//
// Address object
//
class Address {
  String city;
  String state;

  Address({
    this.city,
    this.state
  });

  static fromJson(Map<String, dynamic> parsedJson){
    return Address(
      city: parsedJson["city"],
      state: parsedJson["state"]
    );
  }
}

Once we have the Dart representation of objects ready, we will see how to read and display the JSON object on Flutter app. A stateless widget, SchoolInfoWidget is defined and the build method is used to build the widget / element tree as shown in the diagram later. Pay attention to the code School schoolInfo = School.fromJson(_school) which is passed the JSON object and returns the School DART object.

class SchoolInfoWidget extends StatelessWidget {

  Map<String, dynamic> _school = {
    "name": "IIT Kharagpur",
    "address": {
      "city": "Kharagpur",
      "state": "West Bengal"
    },
    "departments": [
      {"name": "Computer Science",
        "seats": 50
      },
      {"name": "Electronics",
        "seats": 70
      },
      {"name": "Electrical",
        "seats": 80
      },
      {"name": "Mechanical",
        "seats": 100
      },
    ]
  };

  @override
  Widget build(BuildContext context) {
    School schoolInfo =  School.fromJson(_school);
    return ListView(
        children: List.generate(schoolInfo.departments.length,(index){
            return Container(
                padding: const EdgeInsets.fromLTRB(20.0, 10.0, 10.0, 10.0),
                child: Text("Name: " + schoolInfo.departments[index].name.toString() +"\n" "Seats: " + schoolInfo.departments[index].seats.toString())
            );
          })
      );
  }
  
}

Finally, we will load the SchoolInfoWidget in the Flutter app using the following code:

import 'dart:io';

import 'package:device_info/device_info.dart';
import 'package:flutter/material.dart';

import 'School.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Hello World App',
        home: Scaffold(
          appBar: AppBar(
            title: Text('School Information'),
          ),
          body: Center(
            child: SchoolInfoWidget(),
          ),
        ));
  }
}

And, running above app will look like the following in the mobile device.

Fig 1. Flutter App

The code given in this post will be very useful in reading JSON from REST API response as a set of DART objects.

Ajitesh Kumar

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia, etc, and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data, etc. For latest updates and blogs, follow us on Twitter. I would love to connect with you on Linkedin. Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking. Check out my other blog, Revive-n-Thrive.com

Share
Published by
Ajitesh Kumar
Tags: flutter

Recent Posts

Pricing Analytics in Banking: Strategies, Examples

Last updated: 15th May, 2024 Have you ever wondered how your bank decides what to…

4 days ago

How to Learn Effectively: A Holistic Approach

In this fast-changing world, the ability to learn effectively is more valuable than ever. Whether…

6 days ago

How to Choose Right Statistical Tests: Examples

Last updated: 13th May, 2024 Whether you are a researcher, data analyst, or data scientist,…

6 days ago

Data Lakehouses Fundamentals & Examples

Last updated: 12th May, 2024 Data lakehouses are a relatively new concept in the data…

7 days ago

Machine Learning Lifecycle: Data to Deployment Example

Last updated: 12th May 2024 In this blog, we get an overview of the machine…

1 week ago

Autoencoder vs Variational Autoencoder (VAE): Differences, Example

Last updated: 12th May, 2024 In the world of generative AI models, autoencoders (AE) and…

1 week ago