Hi Guys, Welcome to Proto Coders Point.
In this Flutter tutorial(Article), We will learn how to read json file in flutter & parse local JSON file in flutter & the Display the JSON file data in flutter listview builder.
Final Output
Video Tutorial – Example on reading json file, parse json data or fetch json data in flutter
You can watch the above video or continue reading…
So Let’s begin
Implementing flutter read local JSON file from assets folder.
1. Create a new flutter project
Firstly, need to create a new flutter project or simply only any existing flutter project where you want to implement read local JSON file in flutter.
In my case, I make use of android stdio to develop flutter application.
creating new flutter project:
File > New > New Flutter Project.
Give a good name & package name to project and finish.
Done your flutter project is ready.
2. How to add JSON file in flutter project
I have created a JSON file by name ProductItem.json which has a list of 10 shoes products (id, name, category, imageUrl, oldPrice & price of each item).
you can download the json file from below button or simply create you own json file.
Create a directory under flutter project & paste the ProductItem.json file in the directory.
3. Create a data model class file
ProductDataModel.dart is used to handle our data that is been used to read from JSON file.
This class has dataTypes & constructor & a method.
ProductDataModel.fromJson is used to assign the data to variable in MAP json format.
Check out this Post Flutter Auto Create Model from JSON File
ProductDataModel.dart
class ProductDataModel{ //data Type int? id; String? name; String? category; String? imageURL; String? oldPrice; String? price; // constructor ProductDataModel( { this.id, this.name, this.category, this.imageURL, this.oldPrice, this.price } ); //method that assign values to respective datatype vairables ProductDataModel.fromJson(Map<String,dynamic> json) { id = json['id']; name =json['name']; category = json['category']; imageURL = json['imageUrl']; oldPrice = json['oldPrice']; price = json['price']; } }
4. Reading JSON file & display the data in listview
Explanition of what is done in main.dart file.
1. Import services.dart as rootBundle
import 'package:flutter/services.dart' as rootBundle;
This will help us in reading json file.
2. Create Method to read json file in flutter
Future<List<ProductDataModel>> ReadJsonData() async { //read json file final jsondata = await rootBundle.rootBundle.loadString('jsonfile/productlist.json'); //decode json data as list final list = json.decode(jsondata) as List<dynamic>; //map json and initialize using DataModel return list.map((e) => ProductDataModel.fromJson(e)).toList(); }
3. FutureBuilder to parse & display data in listview
FutureBuilder( future: ReadJsonData(), builder: (context, data) { if (data.hasError) { //in case if error found return Center(child: Text("${data.error}")); } else if (data.hasData) { //once data is ready this else block will execute // items will hold all the data of DataModel //items[index].name can be used to fetch name of product as done below var items = data.data as List<ProductDataModel>; return ListView.builder( itemCount: items == null ? 0 : items.length, itemBuilder: (context, index) { return Card( elevation: 5, margin: EdgeInsets.symmetric(horizontal: 10, vertical: 6), child: Container( padding: EdgeInsets.all(8), child: Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Container( width: 50, height: 50, child: Image( image: NetworkImage(items[index].imageURL.toString()), fit: BoxFit.fill, ), ), Expanded( child: Container( padding: EdgeInsets.only(bottom: 8), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: EdgeInsets.only(left: 8, right: 8), child: Text( items[index].name.toString(), style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold), ), ), Padding( padding: EdgeInsets.only(left: 8, right: 8), child: Text(items[index].price.toString()), ) ], ), )) ], ), ), ); }); } else { // show circular progress while data is getting fetched from json file return Center( child: CircularProgressIndicator(), ); } }, )
Complete Code – Read JSON file in flutter & display data on screen using ListView.Builder
main.dart
import 'dart:convert'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:read_json_file/ProductDataModel.dart'; import 'package:flutter/services.dart' as rootBundle; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( body: FutureBuilder( future: ReadJsonData(), builder: (context, data) { if (data.hasError) { return Center(child: Text("${data.error}")); } else if (data.hasData) { var items = data.data as List<ProductDataModel>; return ListView.builder( itemCount: items == null ? 0 : items.length, itemBuilder: (context, index) { return Card( elevation: 5, margin: EdgeInsets.symmetric(horizontal: 10, vertical: 6), child: Container( padding: EdgeInsets.all(8), child: Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Container( width: 50, height: 50, child: Image( image: NetworkImage(items[index].imageURL.toString()), fit: BoxFit.fill, ), ), Expanded( child: Container( padding: EdgeInsets.only(bottom: 8), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: EdgeInsets.only(left: 8, right: 8), child: Text( items[index].name.toString(), style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold), ), ), Padding( padding: EdgeInsets.only(left: 8, right: 8), child: Text(items[index].price.toString()), ) ], ), )) ], ), ), ); }); } else { return Center( child: CircularProgressIndicator(), ); } }, ) ); } Future<List<ProductDataModel>> ReadJsonData() async { final jsondata = await rootBundle.rootBundle.loadString('jsonfile/productlist.json'); final list = json.decode(jsondata) as List<dynamic>; return list.map((e) => ProductDataModel.fromJson(e)).toList(); } }
Output