Sometimes we need to read the local JSON file and show the parsed JSON data to our application. In this post, I'll show you how you can read and parse local JSON data and show it in a listview in your flutter application step by step.
pubspec.yaml
file.
Make an asset folder in your project root directory and put your JSON file into that. For example, our JSON file name is person.json and the content of the file looks like below.
[
{
"name":"Jhon Smith",
"email":"jhon@example.com"
},
{
"name":"Adam",
"email":"adam@example.com"
},
{
"name":"Rhiu",
"email":"rhiu@example.com"
},
{
"name":"Bidu",
"email":"bidu@example.com"
}
]
pubspec.yaml
file.Now open the pubspec.yaml
file and add these on flutter section.
flutter:
assets:
- assets/person.json
import these statements into your dart file.
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
import 'dart:convert';
import 'package:flutter/services.dart';
Make a method to read the JSON file into your flutter application and call the locadJsonData
method into initState
List data;
Future<String> loadJsonData() async {
var jsonText = await rootBundle.loadString('assets/people.json');
setState(() => data = json.decode(jsonText));
return 'success';
}
@override
void initState() {
super.initState();
this.localJsonData();
}
With the help of the loadJsonData
method, our JSON data will be available into List data;
now just render the data with a ListView
widget like below.
new ListView.builder(
itemCount: data == null ? 0 : data.length,
itemBuilder: (BuildContext context, int index) {
var name = data[index]['name'];
var email = data[index]['email'];
return new Column(
children: <Widget>[
new ListTile(
leading: CircleAvatar(
child: new Icon(Icons.account_box),
),
title: Text(name),
subtitle: Text(email),
),
new Divider(),
],
);
});
Hope, this step by step tutorial to read local JSON file in Flutter application will help you to learn how to read and parse JSON file in Flutter application. If you like this tutorial post, please share with others.