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

Last updated Aug 11, 2021


In this flutter tutorial we will learn how to parse JSON data in flutter. In this we will read JSON file from assets folder and fetch the data from the file. I have copied JSON files in Assets folder and fetch the data from that JSON files

 

Let's get started

Step 1: Create flutter application

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<dynamic> list_telugu = response['telugu'];
            List<dynamic> 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        Read files from assets folder

 

 

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<MyHomePage> {
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: <Widget>[
           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: <Widget>[

                ///----------------Item One-----------------------------
                InkWell(
                  onTap:(){
                    loadDetail(context,1);
                  },
                  child: Card(
                      elevation: 15,
                      child: Stack(
                        children: <Widget>[
                          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: <Widget>[
                          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: <Widget>[
                          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: <Widget>[
                          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<DetailsPage> {
  List<Items>list_items;
  var imagepath;

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

          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: <Widget>[
             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: <Widget>[
                  for(final item in list_items)
                      Card(child: Stack(
                           children: <Widget>[

                              Container(color: Colors.white70,),
                              Center(
                               child: Column(
                                 mainAxisSize: MainAxisSize.min,
                                 children: <Widget>[
                                   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<dynamic> list_telugu = response['telugu'];
                List<dynamic> 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);

  static Items fromJson(Map<String,String>map)
  {

  }
}

 

Download Parse JSON data from Assets folder

 

Tags: Flutter, Read local JSON file, Fetch JSON file, Parse JSON data, Gridview

Parse JSON data in flutter, Read JSON Flutter


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

5375 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions