How to read Json in Flutter ? | Examples to read json in Flutter | Parsing JSON data in Flutter

parsing json data in flutter

When developing mobile applications, working with JSON data is a common requirement. Fetching and parsing JSON data can be challenging, especially when dealing with different data structures. In this article, we will delve into the various possibilities that arise when reading and displaying JSON data in Flutter, providing you with a comprehensive guide.

EXAMPLE Parsing JSON data in Flutter

//STEP 1
{
    "items": [
        {
            "id": "123",
            "name": "Apple",
            "type": "dry fruits"
        },
        {
            "id": "456",
            "name": "Walnuts",
            "type": "dry fruits"
        }
    ]
}

// Now, Convert Json to Dart model, through https://javiercbk.github.io/json_to_dart/

//STEP 2
class JsonToDartModel {
  List<Items>? items;

  JsonToDartModel({this.items});

  JsonToDartModel.fromJson(Map<String, dynamic> json) {
    if (json['items'] != null) {
      items = <Items>[];
      json['items'].forEach((v) {
        items!.add(new Items.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.items != null) {
      data['items'] = this.items!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Items {
  String? id;
  String? name;
  String? type;

  Items({this.id, this.name, this.type});

  Items.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    type = json['type'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    data['type'] = this.type;
    return data;
  }
}

Here when ever we received data in Json format we use that json through this model JsonToDartModel

Now below example clearly show how to use this model

//STEP 3

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class YourScreen extends StatefulWidget {
  @override
  _YourScreenState createState() => _YourScreenState();
}

class _YourScreenState extends State<YourScreen> {
  List<dynamic> items = [];

  @override
  void initState() {
    super.initState();
    fetchItems();
  }

// If you are getting data through APi
  Future<void> fetchItems() async {
    final response = await http.get(Uri.parse('API_URL'));
    if (response.statusCode == 200) {
      final jsonData = json.decode(response.body);
      setState(() {
        items = jsonData['items'];
      });
    } else {
      throw Exception('Failed to fetch data');
    }
  }

 //OR
// if you using dummy data
  Future<void> fetchItems() async {
    var dummyJson={
    "items": [
        {
            "id": "123",
            "name": "Apple",
            "type": "dry fruits"
        },
        {
            "id": "456",
            "name": "Walnuts",
            "type": "dry fruits"
        }
    ]
     };
   Map<String, dynamic> map = jsonDecode(dummyJson); 
   JsonToDartModel jsonData = JsonToDartModel.fromJson(map);
      setState(() {
        items = jsonData['items'];
      });
    
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Your App'),
      ),
      body: ListView.builder(
        itemCount: items.length,
        itemBuilder: (context, index) {
          final item = items[index];
          return ListTile(
            title: Text(item['name']),
            subtitle: Text(item['type']),
          );
        },
      ),
    );
  }
}

Replace ‘API_URL‘ with the actual URL of your API endpoint where you are receiving the JSON data.

Create a new screen or widget in your Flutter app, such as YourScreen, where you want to display the data.

Use the http package to fetch the JSON data from the API endpoint inside the fetchItems function.

Decode the JSON response using json.decode(response.body) and store it in the items list.

In the build method, use a ListView.builder widget to display the items. Customize the UI as needed.

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.