Json to Dart in Flutter | Nested Json to dart | List of Json to dart

parsing json data in flutter

Json to Dart in Flutter

Flutter Tutorial

Introduction

Flutter

Cross Platform

MVVM vs MVC vs MVP

Flutter Framework

Flutter Benefits

Flutter Comparison

Install Flutter in Win/Linux/Mac

Android Studio vs VsCode

Android Setup

VS Code Setup

VS Code Plugins

Android Studio Plugins

Flutter Widgets:

Flutter Basic Template

Flutter Commands

Top 10 Popular widgets

Flutter Stateless vs Stateful

Type of Widgets

Flutter Text widget

Flutter Text style

Textfield vs TextFormField

Flutter Scaffold

Flutter Container & SizedBox

Flutter Row & Column

Flutter Buttons

Flutter Stack

Flutter Forms

Flutter AlertDialog

Flutter Icons

Flutter Images

Flutter Drawer

Flutter ListView

Flutter GridView

Flutter Toast

Flutter Checkbox

Flutter Radio Button

Flutter Progress Bar

Flutter Tooltip

Flutter Slider

Flutter Table

Flutter SnackBar

Shimmer in Flutter

Bottom Navigation Bar in Flutter

Gesture Detector in Flutter

Error Handling in Flutter

DropDown in Flutter

Flutter Toggle

Auto Close Keyboard in Flutter

Screen size handling in Flutter

Flutter REST API

Flutter http

Flutter dio

dio vs http

Flutter Advance

Custom widget in Flutter

Flutter Navigator

Read Json in Flutter

Generate Excel in Flutter

Multiple Widgets in Flutter

Bottom sheet in Flutter

Copy to Clipboard in Flutter

Tab bar in Flutter

Code Editor in Flutter

Youtube Player in Flutter

Flutter App Development Tips

Flutter App version Update

Flutter Copy Text in App

Flutter Handle Null Value

Flutter Splash Screen

Flutter Disposable

Notification Listener

Flutter Switch Cases

Flutter Slivers

Flutter Custom App bar

Databinding in Flutter

Flutter Cards

Wrap vs Builder vs OverBarFlow

Flutter App Upgrade

GoogleMap vs FlutterMap

Circular progress contain Icon

DropDown Timer in Flutter

Flutter State management Comparison

Flutter vs Other Framework

Flutter Mixin

Passing values in Dart Files

WorkManager in Flutter

Flutter Database

Flutter Store Data

Suitable DB for Flutter

Backend for Flutter

SharedPreferences in Flutter

Flutter Token Expired Handling

Flutter Provider

Flutter Provider Tutorial

Flutter GetX

Flutter GetX tutorial

Flutter with Native

Flutter FFI

Flutter Testing

Flutter Tips

Best Practices

Reduce Flutter Screens

Tips to make app smart

Optimize App

Handle Multiple Pages

Interview Questions

Flutter 100 Interview Questions

Provider Interview Questions

GetX Interview Questions

BLoC Interview Questions

There are many ways to convert JSON to Dart, one way is json_serializable technology and the other is to convert directly through online platform, in this article we will use the second technique which is an easier way than the first one.

Json to Dart in flutter

To convert any JSON into dart the easiest way is json to dart converter link in which you can paste Json content and it converts Json to dart in a second.

After converting you just need to copy the code and paste it into your Flutter application Sometimes API Response JSON contains null value, you need to check it and replace with real data type

json to dart flutter example
import 'dart:convert';

import 'package:flutter/material.dart';

class ResearchThinkerJsonToDartConverterExample extends StatelessWidget {
  //Dummy json data
  final String jsonData = '''
    {
      "id": 1,
      "name": "Research Thinker",
      "email": "contact@researchthinker.com",
      "address": {
        "street": "123 Main St",
        "city": "Cityville",
        "zipCode": "12345"
      },
      "orders": [
        {"orderId": 101, "product": "Widget A"},
        {"orderId": 102, "product": "Widget B"}
      ]
    }
  ''';

  //common widget for spacing
  commonGap() {
    return SizedBox(
      height: 10,
    );
  }

  @override
  Widget build(BuildContext context) {
    Map<String, dynamic> jsonMap = json.decode(jsonData);
    User user = User.fromJson(jsonMap);

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Research Thinker: "Json to Dart" example'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Center(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'Json to dart',
                  style: TextStyle(
                    decoration: TextDecoration.underline,
                    decorationStyle: TextDecorationStyle.double,
                    fontSize: 30,
                  ),
                ),
                commonGap(),
                commonGap(),
                //Below data display json data
                Text('ID: ${user.id}',
                    style: TextStyle(
                      fontSize: 20,
                    )),
                commonGap(),
                Text('Name: ${user.name}',
                    style: TextStyle(
                      fontSize: 20,
                    )),
                commonGap(),
                Text('Email: ${user.email}',
                    style: TextStyle(
                      fontSize: 20,
                    )),
                commonGap(),
                Text(
                    'Address: ${user.address.street}, ${user.address.city}, ${user.address.zipCode}',
                    style: TextStyle(
                      fontSize: 20,
                    )),
                commonGap(),
                commonGap(),
                Text('Orders:',
                    style: TextStyle(
                      fontSize: 20,
                      decoration: TextDecoration.underline,
                    )),
                commonGap(),
                for (Order order in user.orders)
                  Text(
                      '  - Order ID: ${order.orderId}, Product: ${order.product}',
                      style: TextStyle(
                        fontSize: 20,
                      )),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

//Json to dart classes, generated through json to dart converter

class User {
  final int id;
  final String name;
  final String email;
  final Address address;
  final List<Order> orders;

  User({
    required this.id,
    required this.name,
    required this.email,
    required this.address,
    required this.orders,
  });

  factory User.fromJson(Map<String, dynamic> json) {
    var ordersList = json['orders'] as List;
    List<Order> orders =
        ordersList.map((orderJson) => Order.fromJson(orderJson)).toList();

    return User(
      id: json['id'],
      name: json['name'],
      email: json['email'],
      address: Address.fromJson(json['address']),
      orders: orders,
    );
  }
}

class Address {
  final String street;
  final String city;
  final String zipCode;

  Address({
    required this.street,
    required this.city,
    required this.zipCode,
  });

  factory Address.fromJson(Map<String, dynamic> json) {
    return Address(
      street: json['street'],
      city: json['city'],
      zipCode: json['zipCode'],
    );
  }
}

class Order {
  final int orderId;
  final String product;

  Order({
    required this.orderId,
    required this.product,
  });

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

Conclusion: In this article we easily converted JSON to Dart and integrate into Flutter application, similarly you can convert any JSON to Dart and use in your application.

Leave a Reply

Your email address will not be published. Required fields are marked *

web_horizontal
About Us ♢ Disclaimer ♢ Privacy Policy ♢ Terms & Conditions ♢ Contact Us

Copyright © 2023 ResearchThinker.com. All rights reserved.