Use Local JSON in Flutter

Create Free Backend With Appwrite

Introduction

In this section, you will learn how to use local JSON in your flutter application with the help of real-world example. Before we start, make sure you have basic knowledge of JSON. If you don’t know start from here.

Example 1: Profile App

In this example, you will learn to create a profile app using local JSON. Here are the steps to create a app:

Step 1: Add the JSON File

To use local JSON in your app, the first step is to add the JSON file in your project folder/assets/data. You can download sample JSON file from here or you can use your own JSON file.

Step 2: Add JSON File to Your Project

In project folder, create a new folder called assets and inside assets folder, create another folder called data. Now, place the JSON file inside the data folder. Here is preview of the folder structure:

json_in_flutter/
├── assets/
│   └── data/
│       └── info.json
├── lib/
│   └── main.dart
Step 3: Add JSON File to pubspec.yaml File

Now, you need to add JSON file to the pubspec.yaml file. Go to your pubspec.yaml file and add the following code in it:

flutter:
  assets:
    - assets/data/info.json
Step 4: Create Model Class

Now, you need to create a model class for the JSON data. Create a new file called person.dart inside lib folder and add the following code in it:

class Person {
  final String name;
  final String address;
  final int age;
  final String image;
  final String description;

// Constructor
  Person(
      {required this.name,
      required this.address,
      required this.age,
      required this.image,
      required this.description});

// Convert JSON to Person Object
  factory Person.fromJson(Map<String, dynamic> json) {
    return Person(
      name: json['name'],
      address: json['address'],
      age: json['age'],
      image: json['image'],
      description: json['description'],
    );
  }
}
Step 5: Load and Decode the JSON File

Now create a new file called localservice.dart inside lib folder and add the following code in it:

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

class LocalService {
    // Load and decode the JSON File
  Future<String> _loadPersonAsset() async {
    return await rootBundle.loadString('assets/data/info.json');
  }

  // Load and decode the JSON File  
  Future<Person> loadPerson() async {
    String jsonString = await _loadPersonAsset();
    // json.decode() is used to convert JSON String to JSON Map
    final jsonResponse = json.decode(jsonString);
    return Person.fromJson(jsonResponse);
  }
}
Step 6: Display the JSON Data

Now, you can use the LocalService class to display the JSON data. Here is how you can use it on your main.dart file:

import 'package:flutter/material.dart';
import 'localservice.dart';
import 'person.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    const appTitle = 'JSON in Flutter';

    return MaterialApp(
      title: appTitle,
      home: Scaffold(
        appBar: AppBar(
          title: const Text(appTitle),
        ),
        body: FutureBuilder(
          future: LocalService().loadPerson(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              Person person = snapshot.data as Person;
              return Center(
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Card(
                    elevation: 4.0,
                    child: Padding(
                      padding: const EdgeInsets.all(16.0),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          CircleAvatar(
                            backgroundImage: NetworkImage(person.image),
                            radius: 50.0,
                          ),
                          const SizedBox(height: 10),
                          Text(
                            person.name,
                            style: const TextStyle(
                              fontSize: 24,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 5),
                          Text(
                            person.address,
                            style: TextStyle(
                              fontSize: 16,
                              color: Colors.grey[600],
                            ),
                          ),
                          const SizedBox(height: 5),
                          Text(
                            'Age: ${person.age}',
                            style: TextStyle(
                              fontSize: 16,
                              color: Colors.grey[800],
                            ),
                          ),
                          const SizedBox(height: 10),
                          Text(
                            person.description,
                            textAlign: TextAlign.center,
                            style: const TextStyle(
                              fontSize: 16,
                              fontStyle: FontStyle.italic,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              );
            } else {
              return const Center(child: CircularProgressIndicator());
            }
          },
        ),
      ),
    );
  }
}

Supporting Source Code

If you face any issue while using the fonts, then you can check this link for the complete source code.

Challenge

Create quote app using local JSON. Use this JSON file to display the quotes.