JSON is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and arrays.
Becuase of it's human readability and with it being lightweight, it is commonly used as an easy data storage format. That means it can be used also in ways not involving data exchange but also a form of database.
In this tutorial we want to see how to load data from a local JSON file. For example you may download a list of products in form JSON and may want to render them in your Flutter app. Well then this tutorial is helpful in showing you how to do that.
Here is the demo of the created project:
Step 1: Create A Flutter project
Start by creating a flutter project in your favorite editor or IDE.
Step 2: Prepare JSON Data
Download this demo JSON data. Copy the JSON file in a folder known as data_repo
, then copy that folder in the root folder of your project.
YOUR_PROJECT/data_repo/starwars_data.json
Then in your pubspec.yaml
, register that data as an asset:
assets:
- data_repo/starwars_data.json
Step 3: Dependencies
No third party dependency is needed. Below is our complete pubspec.yaml
;
name: load_local_json
description: A new Flutter project.
dependencies:
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
assets:
- data_repo/starwars_data.json
Step 4: Write Code
Start by importing both the material.dart
and convert
packages:
import 'dart:convert';
import 'package:flutter/material.dart';
In our main function we will run our MyApp
instance. This is the entry point to our application:
void main() {
runApp(new MaterialApp(
home: new MyApp(),
));
}
Create a StatefulWidget called MyApp
:
class MyApp extends StatefulWidget {
@override
MyAppState createState() => new MyAppState();
}
Now create our MyApp state class by extending the State
base class:
class MyAppState extends State<MyApp> {
In this class we will have one instance field, a List called data
:
List data;
Now build a widget which will contain and represent our screen components:
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Load local JSON file"),
),
We will also construct the body of the screen. To load our local JSON as assets, we will use DefaultAssetBundle
and FutureBuilder
classes:
body: new Container(
child: new Center(
// Use future builder and DefaultAssetBundle to load the local JSON file
child: new FutureBuilder(
future: DefaultAssetBundle
.of(context)
.loadString('data_repo/starwars_data.json'),
builder: (context, snapshot) {
We will then decode the JSON data into a variable:
// Decode the JSON
var new_data = json.decode(snapshot.data.toString());
Then bind it to a ListView:
return new ListView.builder(
// Build the ListView
itemBuilder: (BuildContext context, int index) {
The ListView will comprise Cards, with each row containing a Card with data:
return new Card(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
new Text("Name: " + new_data[index]['name']),
new Text("Height: " + new_data[index]['height']),
new Text("Mass: " + new_data[index]['mass']),
new Text(
"Hair Color: " + new_data[index]['hair_color']),
new Text(
"Skin Color: " + new_data[index]['skin_color']),
new Text(
"Eye Color: " + new_data[index]['eye_color']),
new Text(
"Birth Year: " + new_data[index]['birth_year']),
new Text("Gender: " + new_data[index]['gender'])
],
),
);
},
itemCount: new_data == null ? 0 : new_data.length,
);
}),
),
));
}
}
Here is the full code:
main.dart
import 'dart:convert';
import 'package:flutter/material.dart';
void main() {
runApp(new MaterialApp(
home: new MyApp(),
));
}
class MyApp extends StatefulWidget {
@override
MyAppState createState() => new MyAppState();
}
class MyAppState extends State<MyApp> {
List data;
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Load local JSON file"),
),
body: new Container(
child: new Center(
// Use future builder and DefaultAssetBundle to load the local JSON file
child: new FutureBuilder(
future: DefaultAssetBundle
.of(context)
.loadString('data_repo/starwars_data.json'),
builder: (context, snapshot) {
// Decode the JSON
var new_data = json.decode(snapshot.data.toString());
return new ListView.builder(
// Build the ListView
itemBuilder: (BuildContext context, int index) {
return new Card(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
new Text("Name: " + new_data[index]['name']),
new Text("Height: " + new_data[index]['height']),
new Text("Mass: " + new_data[index]['mass']),
new Text(
"Hair Color: " + new_data[index]['hair_color']),
new Text(
"Skin Color: " + new_data[index]['skin_color']),
new Text(
"Eye Color: " + new_data[index]['eye_color']),
new Text(
"Birth Year: " + new_data[index]['birth_year']),
new Text("Gender: " + new_data[index]['gender'])
],
),
);
},
itemCount: new_data == null ? 0 : new_data.length,
);
}),
),
));
}
}
Step 5: Run
- Prepare JSON data as has been discussed above.
- Copy the code above into your
main.dart
. - Run