Flutter - Read Json file from assets folder and parse JSON data

Last updated Aug 09, 2022

In this flutter tutorial we will learn how to read json data from assets folder and parse JSON data in flutter. In this application we will read a local json file. We have 3 steps

  • Create Assets folder and Add Json file
  • Update pubspec.yaml file to configure json file path
  • Read Data from assets folder and parse the data

This Article will cover below flutter JSON questions

  • How do I load a JSON file from assets folder in flutter?
  • How do you call a JSON in flutter?
  • How do I read a JSON file in flutter?
  • How do you read JSON in darts?
  • What is JSON decode in flutter?
  • How do I import a JSON file into flutter?
  • How do you use mock JSON in flutter?

Let's get started

Step 1: Create flutter application in Android studio. Refer How to create first Flutter application in android studio

Step 2: Add required json files inside assets folder

Step 3: Define assets inside pubspec.yaml file to access inside application

assets:
  - spices.json
  - vegetable.json

              

Step 4: Read JSON from assets folder

Now we will use DefaultAssetBundle.of(context).loadString() method to read json file from assets folder

 

Step 5: From the above method it will return json string, now we need to read data from the json and parse json data and display on UI screen.

await DefaultAssetBundle.of(context).loadString("assets/$file")
    .then((s) {
          setState(() {

          var response = json.decode(s);
            List list_telugu = response['telugu'];
            List list_english = response['english'];

                for (var k = 0; k < list_telugu.length; k++) {
                  list_items!.add(Items(list_english[k], list_telugu[k]));
                }


           });
    }).catchError((error) {

      print(error);
    });

 

 

Parse JSON data from assets folder

        

How to Read files from assets folder in Flutter

 

 

Complete code

main.dart file

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

import '../details.dart';
import 'model/items.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
Size? size;
  @override
  Widget build(BuildContext context) {
    size=MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: Colors.grey,
      appBar: AppBar(
        backgroundColor: Colors.pink,
        title: Text("Spices & Vegitables"),
      ),
      body: Stack(
        children: [
           Container(
             width: double.infinity,
             height: double.infinity,
             decoration: BoxDecoration(
               borderRadius: BorderRadius.only(
                   bottomRight: Radius.elliptical( size!.width, size!.width),
                   topRight: Radius.circular(size!.width/2),
                   topLeft: Radius.circular(size!.width/2),
               ),
               color: Colors.white54
             ),
           ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: GridView.count(
              mainAxisSpacing: 10,
              childAspectRatio: 320/470,
              crossAxisCount: 2,
              crossAxisSpacing: 5,
              children: [

                ///----------------Item One-----------------------------
                InkWell(
                  onTap:(){
                    loadDetail(context,1);
                  },
                  child: Card(
                      elevation: 15,
                      child: Stack(
                        children: [
                          Image.asset("spices.png", fit: BoxFit.cover,height: 320,),

                            Align(
                              alignment:Alignment.bottomCenter,

                              child:  Container(width:double.infinity,color:Colors.white70,child: Text( "Spices\n View",style: TextStyle(color: Colors.pink,fontSize: 20,fontStyle: FontStyle.italic),textAlign: TextAlign.center  )),
                            ),


                        ],
                      )

                  ),

                ),

                ///----------------Item two-----------------------------

                InkWell(
                  onTap:(){
                    loadDetail(context,2);
                  },
                  child: Card(
                      elevation: 15,
                      child: Stack(
                        children: [
                          Image.asset("dry_fruite.png", fit: BoxFit.cover,height:320,),

                          Align(
                            alignment:Alignment.bottomCenter,
                            child:  Container(width:double.infinity,color:Colors.white70,child: Text( "Dry Fruites\n View",style: TextStyle(color: Colors.pink,fontSize: 20,fontStyle: FontStyle.italic) ,textAlign: TextAlign.center )),
                          ),


                        ],
                      )

                  ),

                ),

                ///----------------Item three-----------------------------
                InkWell(
                  onTap:(){
                    loadDetail(context,3);
                  },
                  child: Card(
                      elevation: 15,
                      child: Stack(
                        children: [
                          Image.asset("vegetables.png", fit: BoxFit.cover,height: 320,),

                          Align(
                            alignment:Alignment.bottomCenter,
                            child:  Container(width:double.infinity,color:Colors.white70,child: Text( "Vegetables \n View",style: TextStyle(color: Colors.pink,fontSize: 20,fontStyle: FontStyle.italic),textAlign: TextAlign.center  )),
                          ),


                        ],
                      )

                  ),

                ),

                    ///----------------Item Four-----------------------------

                InkWell(
                  onTap:(){
                    loadDetail(context,4);
                  },
                  child: Card(
                      elevation: 15,
                      child: Stack(
                        children: [
                          Image.asset("pulses.png", fit: BoxFit.cover,height: 320,),

                          Align(
                            alignment:Alignment.bottomCenter,
                            child:  Container(width:double.infinity,color:Colors.white70,child: Text( "Pulses \n View",style: TextStyle(color: Colors.pink,fontSize: 20,fontStyle: FontStyle.italic,),textAlign: TextAlign.center,  )),
                          ),


                        ],
                      )

                  ),

                ),


              ],
            ),
          ),
        ],

      ),
    );
  }

  loadDetail(BuildContext ctx,position)
  {
    Navigator.push(ctx, MaterialPageRoute(builder: (_){

      return DetailsPage(position);
    }));
  }
}

 

details.dart

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

import 'model/items.dart';



class DetailsPage extends StatefulWidget {

  int position;
  DetailsPage(this.position);
  @override
  State createState() {
    return DetailsState();
  }
}

class DetailsState extends State {
  List?list_items;
  var imagepath;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
          list_items = List.empty(growable: true);

          if(this.widget.position==1)
            imagepath= "spices.png";
          if(this.widget.position==2)
            imagepath= "dry_fruite.png";
          if(this.widget.position==3)
            imagepath= "vegetables.png";
          if(this.widget.position==4)
            imagepath= "dry_fruite.png";

    readData(this.widget.position);

  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build

    return Scaffold(
      backgroundColor: Colors.white70,
        appBar: AppBar(
          backgroundColor: Colors.pink,
          leading: InkWell(child: Icon(Icons.arrow_back,color: Colors.white),
          onTap: (){
            Navigator.pop(context);
          },),
        ),
        body: Stack(

          children: [
             Container(color: Colors.grey[500],),
             Image.asset(imagepath, fit: BoxFit.cover,height: double.infinity,),
                Padding(
                padding: const EdgeInsets.all(8.0),
                child: (list_items!.length==0)?Center(child: CircularProgressIndicator(),):GridView.count(crossAxisCount: 2,
                  children: [
                  for(final item in list_items!)
                      Card(child: Stack(
                           children: [

                              Container(color: Colors.white70,),
                              Center(
                               child: Column(
                                 mainAxisSize: MainAxisSize.min,
                                 children: [
                                   Text(item.name_telugu,style: TextStyle(color: Colors.pink,fontSize: 18),),
                                   Text(item.name_english,style: TextStyle(color: Colors.pink,fontSize: 18),),
                                 ],
                               ),
                             ),
                          ],
                      ),
                      )
                 ],),
              ),
           ],

        ),
    );
  }

  readData(int which) async
  {
    String? file;
          switch(which)
          {
            case 1:
              file="spices.json";
              break;
            case 2:
              file="dry_fruites.json";
              break;
            case 3:
              file="vegetable.json";
              break;
            case 4:
              file="pulses.json";
              break;
          }
    await DefaultAssetBundle.of(context).loadString("assets/$file")
        .then((s) {
              setState(() {

              var response = json.decode(s);
                List list_telugu = response['telugu'];
                List list_english = response['english'];

                    for (var k = 0; k < list_telugu.length; k++) {
                      list_items!.add(Items(list_english[k], list_telugu[k]));
                    }


               });
        }).catchError((error) {

          print(error);
        });
  }
}

 

 

item.dart model class

import 'package:flutter/material.dart';

class Items{
  String name_english;
  String name_telugu;

  Items(this.name_english,this.name_telugu);

 
}

 

Download code for Read Local JSON file in Flutter

 

Conclusion: In this flutter application we implemented how to read local json from assets folder and parse local json data.

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

7374 Views