Favourite List
Nothing Added.

Flutter Read Local JSON File and Display in Listview

Read Local Json File Flutter
Reading and parsing local JSON data is very simple in Flutter. In fact, it takes just two four lines of code to set up access local JSON data as Future async function and make a List for Json Data. In this article, we're going to show you how we can read and parse JSON files locally and show the data in a listview. By following this tutorial you will be able to implement the code in your flutter application very easily. Let's get started.

Add local Json in Flutter Assets:

The JSON file contains information with Key Value pairs. If you open your JSON file , you will see something like below. Here is a sample.json file we are using to easily understand the method.

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

Add "assets" folder on your project and move sample.json into it. Now, declare the json file in the assets section in your pubspec.yaml file like this.

# The following section is specific to Flutter packages.
flutter:
uses-material-design: true
assets:
- assets/
# - images/a_dot_ham.jpeg

Flutter Function for Read Json:

This is the function that responsible for fetching data from local JSON file and put JSON data into List. Place it before widget build. You have to import service and convert package to make it work.


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"];
});
print(_items);
}

This Future Function will get data from local json file and put it into List. When this function called , then it will do it works. We will call it in our app initial state(Our app first run). For that we have to override our init method and call our function. To override init state use this method under list like this.

Override init state


Now our function is called , if you run this project  you will see the json file loaded on debug concole. To show it on our app UI  we will use ternary operator. Ternary operator is an if else function but instead of writing it uses ? for if and : for else. So the explaination of this logic is,'If our list is not empty then show The list in Card Widget else show Circular Progress indicator to the user."


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

class ReadJson extends StatefulWidget {
const ReadJson({Key? key}) : super(key: key);

@override
State<ReadJson> createState() => _ReadJsonState();
}

class _ReadJsonState extends State<ReadJson> {
List _items = [];
@override
void initState() {
super.initState();
readJson();
}

// 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"];
});
print(_items);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Read Json'),
),
body: Padding(
padding: const EdgeInsets.all(25),
child: _items.isNotEmpty
? Column(
children: [
Expanded(
child: ListView.builder(
itemCount: _items.length,
itemBuilder: (context, index) {
return Card(
margin: const EdgeInsets.all(10),
child: ListTile(
leading: Text(_items[index]["id"]),
title: Text(_items[index]["name"]),
subtitle: Text(_items[index]["description"]),
),
);
},
),
)
],
)
: Center(child: CircularProgressIndicator())),
);
}
}


Final Result

So our project will run like this. Here is the result.

Download Full Project and Practice:

We provide source codes for every project. Here is the source code for this project. Download and play with it. Dont forget to follow our github profie.

Wrapping Up

In this tutorial, I have shown you how to create a sample flutter project and how to parse local JSON file to convert it into a list. If you have any queries about this post then please let me know in the comments below and share it to friends. This is simple json file, what if our json file is as big as all the words of Oxford Dictionary? Will it works or not? How could you can handle it? To learn more we will show you how to parse the complex large json with Model. For API data you can read this. Thank You.

Next Post Previous Post
Feels like
No Comment
Add Comment
comment url