Press "Enter" to skip to content

Flutter: How to Read Json File from Assets

Reading a json file from Server API is an already discussed topic. On previous article we learnt how to read a text file from assets. On this tutorial, we discuss how to read a json file and fetch the content from assets. If you are focusing an application with static contents, then storing contents on json file is a best solution.

Reading and fetching json file is almost similar to reading a text file.

Create a json file and type the content that you want to use on your application.

This is a sample: File name is content.json

Creating a json file for Flutter

Place the file on the assets and import the file on pubspec.yaml. See previous article for more about this step.

On Pubspec.yaml, you need to import the json file from asset

  assets:
    - assets/mydata.json

Reading a json file is exact same reading a text file. So by reading previous article, hope you got the idea.

Future<void> readText() async {
    final String response = await rootBundle.loadString('assets/mydata.txt');
    setState(() {
      dataFromFile = response;
    });
  }

But fetching json data from content is something different.

You need to import ‘convert’ package.

import 'dart:convert';

Read and Fetch Json Content

 List _items = [];

  Future<void> readJson() async {
    final String response = await rootBundle.loadString('assets/mydata.json');
    final data = await json.decode(response);
    setState(() {
      _items = data["items"];
    });
  }
  • Where List _items = [];
    -is the list that we want to keep the data from json file.
  • final String response = await rootBundle.loadString(‘assets/mydata.json’);
    – This line is just reading the content of the json file like we read content from normal text files.
  • final data = await json.decode(response);
    – data is decorded to the variable ‘data‘.
  • _items = data[“items”];
    – Finally data is inserted into the list ‘_items‘ and ‘item‘ inside data[‘items’] is the variable name on the json file. See the json data.

Get a Single Json Data

You need to loop to get single value

 for (Map item in _items) {      
        print('Item is :' + item['fruit'].toString());
    }

With condition

 for (Map item in _items) {
      if(item['fruit'] == 'banana')
        print('color is :' + item['color'].toString());
    }

Preview Json Data

On build section, we use ListView Builder to print the data as list items.

ListView.builder(
          itemCount: _items.length,
          itemBuilder: (BuildContext context, int index) {
            return Container(
              child: Column(
                children: [
                  ListTile(
                    title: Text(_items[index]["fruit"]),
                    subtitle: Text('Color is' + _items[index]["color"] ),
                  ),
                  Divider(),
                ],
              ),
            );
          }
      ),
  • itemCount: _items.length,
    – itemCount should be the length of the list ‘_items‘ that we have imported from json file.

Where ‘fruits‘ and ‘color‘ are the data from the json file.

Full Code

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Read Json Data';

    return MaterialApp(
      title: appTitle,
      home: Scaffold(
        appBar: AppBar(
          title: Text(appTitle),
        ),
        body: ReadJson(),
      ),
    );
  }
}
class ReadJson extends StatefulWidget {
  const ReadJson({Key? key}) : super(key: key);

  @override
  _ReadJsonState createState() => _ReadJsonState();
}

class _ReadJsonState extends State<ReadJson> {
  List _items = [];

  Future<void> readJson() async {
    final String response = await rootBundle.loadString('assets/mydata.json');
    final data = await json.decode(response);
    setState(() {
      _items = data["items"];
    });
  }

  @override
  Widget build(BuildContext context) {
    readJson();
    return Container(
      child:
      ListView.builder(
          itemCount: _items.length,
          itemBuilder: (BuildContext context, int index) {
            return Container(
              child: Column(
                children: [
                  ListTile(
                    title: Text(_items[index]["fruit"]),
                    subtitle: Text('Color is : ' + _items[index]["color"] ),
                  ),
                  Divider(),
                ],
              ),

            );
          }

      ),

    );
  }
}

Sample Output:

Place a comment if you have any doubt.

Note:

If your json data contains multiple line and Unicode symbols, then this method may not work. Then follow these changes: Read and display rich content from json

Be First to Comment

Leave a Reply