メインコンテンツまでスキップ

Flutter - How to Load local JSON into ListView

Flutter is a popular mobile development framework that allows developers to build high-quality, cross-platform apps with ease. One of the most common tasks in mobile app development is loading data from an API and displaying it in a user-friendly format. In this article, we will explore how to load JSON data from an API into a ListView in Flutter.

Whether you're a seasoned developer or just getting started with Flutter, this article will provide you with the knowledge you need to get started with loading and displaying JSON data in your app. So, let's dive in!

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is a text format that is completely language independent and is used to transmit data between a server and a web application as an alternative to XML. JSON is often used as a data format for APIs (Application Programming Interfaces) and is supported by most modern programming languages. It consists of key-value pairs and arrays that are nested within each other, similar to the structure of objects in many programming languages.

General Steps

Here ar some general steps on how to load JSON data into a ListView in Flutter.

  1. Create a model class that matches the structure of your JSON data.
  2. Use the http package to fetch the JSON data from a server or local file.
  3. Parse the JSON data using the json.decode() method and convert it to a list of model objects.
  4. Create a ListView.builder widget in your Flutter app.
  5. In the itemBuilder property of the ListView.builder, use the model objects to populate each item in the list.

Here's some sample code that demonstrates these steps:

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

class MyModel {
final String name;
final int age;

MyModel({required this.name, required this.age});

factory MyModel.fromJson(Map<String, dynamic> json) {
return MyModel(
name: json['name'],
age: json['age'],
);
}
}

class MyHomePage extends StatefulWidget {

_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
List<MyModel> _data = [];


void initState() {
super.initState();
_loadData();
}

Future<void> _loadData() async {
final response = await http.get(Uri.parse('https://my-json-server.typicode.com/typicode/demo/posts'));
if (response.statusCode == 200) {
final List<dynamic> jsonData = json.decode(response.body);
setState(() {
_data = jsonData.map((json) => MyModel.fromJson(json)).toList();
});
} else {
throw Exception('Failed to load data');
}
}


Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My App'),
),
body: ListView.builder(
itemCount: _data.length,
itemBuilder: (BuildContext context, int index) {
final item = _data[index];
return ListTile(
title: Text(item.name),
subtitle: Text('Age: ${item.age}'),
);
},
),
);
}
}

In this example, we have a MyModel class that represents each item in our JSON data. We fetch the data using http.get, parse it using json.decode, and convert it to a list of MyModel objects. We then use a ListView.builder widget to display the data in a list, using the itemBuilder property to populate each item with the appropriate data.

More Examples

Here is the demo of the created project:

Flutter Load Local JSON

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 {

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:

  
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 {

MyAppState createState() => new MyAppState();
}
class MyAppState extends State<MyApp> {
List data;

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

  1. Prepare JSON data as has been discussed above.
  2. Copy the code above into your main.dart.
  3. Run