How to read data from local JSON files in Flutter

Last updated on April 16, 2021 A Goodman Loading... Post a comment

This is a short and straight-to-the-point article that shows you how to read local JSON files in Flutter.

Overview

We’ll make a tiny Flutter app that loads and displays some data from a JSON file called sample.json.

Screenshot:

Here’s sample.json:

{
  "items": [
    {
      "id": "p1",
      "name": "Item 1",
      "description": "Description 1"
    },
    {
      "id": "p2",
      "name": "Item 2",
      "description": "Description 2"
    },
    {
      "id": "p3",
      "name": "Item 3",
      "description": "Description 3"
    }
  ]
}

The code which is used to fetch data from the json file (see the full code below):

Future<void> readJson() async {
    final String response = await rootBundle.loadString('assets/sample.json');
    final data = await json.decode(response);
    // ... 
}

To use json.decode(), we need to import dart:convert.

Getting Started

1. Create a new Flutter project:

flutter create local_json_example

2. Create a folder called assets (the name doesn’t matter) in the root directory of your project then copy the sample.json file into it:

3. Declare the the json file in the assets section in your pubspec.yaml file:

flutter:
  assets:
    - assets/sample.json

Note that the indentation is mandatory.

4. Remove all the default code in main.dart and add this:

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

import 'package:flutter/services.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Hide the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List _items = [];

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

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(
          'Kindacode.com',
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(25),
        child: Column(
          children: [
            ElevatedButton(
              child: Text('Load Data'),
              onPressed: readJson,
            ),

            // Display the data loaded from sample.json
            _items.length > 0
                ? Expanded(
                    child: ListView.builder(
                      itemCount: _items.length,
                      itemBuilder: (context, index) {
                        return Card(
                          margin: EdgeInsets.all(10),
                          child: ListTile(
                            leading: Text(_items[index]["id"]),
                            title: Text(_items[index]["name"]),
                            subtitle: Text(_items[index]["description"]),
                          ),
                        );
                      },
                    ),
                  )
                : Container()
          ],
        ),
      ),
    );
  }
}

5. Launch a simulator and run the following command:

flutter run

Output:

Conclusion

We’ve built a simple app that loads data from a local JSON file. Continue exploring more about JSON stuff and other fascinating things in Flutter by reading also:

You can also check out our Flutter topic page or Dart topic page for the latest tutorials and examples.

Related Articles

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x