Flutter Local Json Implementation Tutorial For Beginners

 

Flutter Local Json :

Flutter Local Json implementation, usage in flutter app is explained in this part of the tutorial where we add a local json file to the project and fetch the user details and populate it on to the screen using a list.

Local json can also be used as a testing scenarios like mock api while testing the app to check whether the implementation’s  in the app features work’s or not, it acts in the same way as live api also its useful in mock testing scenarios.

Also it helps you to structure your app without wasting any time (waiting for the real time Api) and provides you ample time for integrations and can just replace the real time api in place of flutter local json.

The parsing scenario is similar interms of both local and global json file so it can be easily used to avoid multiple api calls when the app is in testing phase like payment, sms gateway integrations where the cost incurred is more.

 

pubspec.yaml :

Add the json file to the pubspec file

assets:
   - assets/user.json

 

Flutter local json video tutorial :

Go through the below tutorial for more details on implementation

 

user.json :

We are providing user data with name, number & email fields to the json file in the assets folder.

[
  {
    "name": "Abhishek",
    "number": "9876543210",
    "email": "abhi@gmail.com"
  },
  {
    "name": "Abc",
    "number": "9876543210",
    "email": "abc@gmail.com"
  },
  {
    "name": "def",
    "number": "9876543210",
    "email": "def@gmail.com"
  },
  {
    "name": "ghi",
    "number": "9876543210",
    "email": "ghi@gmail.com"
  },
  {
    "name": "jkl",
    "number": "9876543210",
    "email": "jkl@gmail.com"
  }
]

 

main.dart :

Initialize with the void main() and provide the default class MyApp enclosed inside a MaterialApp

void main() {
  runApp(MaterialApp(
    home: MyApp(),
  ));
}

 

Create a state for the MyApp class extending StatefulWidget so that we can re create the state

class MyApp extends StatefulWidget {
  @override
  MyAppState createState() => MyAppState();
}

 

Declare a variable

late List data;

 

Specify the appBar with title

appBar: AppBar(
  title: Text("Load local JSON file"),
),

 

With the use of a List Builder populate the data form the json on to the screen according to the position also we will use future builder to fetch the data from flutter local json and populate.

ListView.builder(
  // Build the ListView
  itemBuilder: (BuildContext context, int index) {
    return Card(
      child: Padding(
        padding: EdgeInsets.all(20.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Text("Name: " + new_data[index]['name']),
            SizedBox(height: 10,),
            Text("Number: " + new_data[index]['number']),
            SizedBox(height: 10,),
            Text("Email: " + new_data[index]['email'])
          ],
        ),
      ),
    );
  },
  itemCount: new_data == null ? 0 : new_data.length,
);

 

FullCode :

Providing the full code for integration of local json in your flutter app

import 'dart:convert';

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  MyAppState createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  List data;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Load local JSON file"),
        ),
        body: Container(
          child: Center(
            // Use future builder and DefaultAssetBundle to load the local JSON file
            child: FutureBuilder(
                future: DefaultAssetBundle
                    .of(context)
                    .loadString('assets/user.json'),
                builder: (context, snapshot) {
                  // Decode the JSON
                  var new_data = json.decode(snapshot.data.toString());

                  return ListView.builder(
                    // Build the ListView
                    itemBuilder: (BuildContext context, int index) {
                      return Card(
                        child: Padding(
                          padding: EdgeInsets.all(20.0),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.stretch,
                            children: <Widget>[
                              Text("Name: " + new_data[index]['name']),
                              SizedBox(height: 10,),
                              Text("Number: " + new_data[index]['number']),
                              SizedBox(height: 10,),
                              Text("Email: " + new_data[index]['email'])
                            ],
                          ),
                        ),
                      );
                    },
                    itemCount: new_data == null ? 0 : new_data.length,
                  );
                }),
          ),
        ));
  }
}

 

Flutter local json output :

This screen below depicts the implementation of flutter local json

flutter local json

If you have any queries on this tutorial on flutter local json do let us know in the comment section below.If you like this tutorial do like and share us for more interesting updates.

 

Show Buttons
Hide Buttons
Read previous post:
Flutter Stepper Tutorial For Beginners

  Flutter Stepper : Flutter stepper will help you to guide the user through the process intended by the app...

Close