JSON data exchange format is used in all the mobile applications to transfer information between two nodes Client and Server. Using JSON we can transfer hundreds of records in a single object within a few seconds and process them. In this tutorial we would Flutter Create JSON Parse ListView using ListTile widget in Android iOS app. ListView widget is used to show multiple items in a single linear list format. ListTile is a sub part of ListView because it can hold two types of text with fixed height width based format. ListTile has a property leading which is used to add Icon in front of every List item. So let’s get started 🙂 .
Note: We are using JSONPlaceholder online JSON for testing purpose website URL in our app. The URL of JSON is jsonplaceholder.typicode.com/users. There are 10 user records are present in this JSON file.
Screenshot of JSON:
Contents in this project Flutter Create JSON Parse ListView using ListTile Android iOS Example Tutorial:
1. Configure http.dart package for Flutter Android iOS Project:
1. The http.dart package is one of the most commonly used package in Flutter apps for data exchange between two nodes. The http package dose not come with flutter project, We have to manually install the http.dart package in our flutter project. So open your project’s pubspec.yaml file in any text editor.
2. Open the pubspec.yaml file in code editor and find dependencies line and put http: ^0.12.0 in next line like i did in below screenshot.
1 2 3 4 |
dependencies: http: ^0.12.0 flutter: sdk: flutter |
Complete Source code for my pubspec.yaml file after done changes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
name: app description: A new Flutter project. version: 1.0.0+1 environment: sdk: ">=2.1.0 <3.0.0" dependencies: http: ^0.12.0 flutter: sdk: flutter cupertino_icons: ^0.1.2 dev_dependencies: flutter_test: sdk: flutter flutter: uses-material-design: true |
3. After done saving the file, We have to open our flutter project Root directory in Command Prompt or Terminal and execute flutter pub get command. This command would download the newly added HTTP package in our flutter project.
1. Import material.dart, dart:convert, http.dart package in your app’s main.dart file.
1 2 3 |
import 'package:flutter/material.dart'; import 'dart:convert'; import 'package:http/http.dart' as http; |
2. Creating void main runApp() method and here we would call our main Root MyApp class.
1 |
void main() => runApp(MyApp()); |
3. Creating main class named as MyApp extends with State less widget. In this class we would call JSONListView class which we would make in next few steps.
1 2 3 4 5 6 7 8 9 10 11 |
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: Center( child: JSONListView() ), )); } } |
4. Create a class named as GetUsers. Inside this class we would make 4 different type of variable named as id, name, email, phoneNumber. We would make factory GetUsers.fromJson() method in this class and here we would pop up the JSON items form online JSON. The name pass in json[] should be same as passed in JSON file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class GetUsers { int id; String name; String email; String phoneNumber; GetUsers({ this.id, this.name, this.email, this.phoneNumber }); factory GetUsers.fromJson(Map<String, dynamic> json) { return GetUsers( id: json['id'], name: json['name'], email: json['email'], phoneNumber: json['phone'] ); } } |
5. Create a class named as JSONListView extends StatefulWidget. In this class we would make the createState() method of State and pass the next CustomJSONListView class with it.
1 2 3 |
class JSONListView extends StatefulWidget { CustomJSONListView createState() => CustomJSONListView(); } |
6. Create a class named as CustomJSONListView extends with State. This is our main ListView parsing class.
1 2 3 4 |
class CustomJSONListView extends State { } |
7. Creating a final String variable named as apiURL. In this variable we would pass our JSON API URL.
1 |
final String apiURL = 'https://jsonplaceholder.typicode.com/users'; |
8. Create a Future ASYNC function named as fetchJSONData() along with GetUsers class works as List. In this function we would pass the complete JSON.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
Future<List<GetUsers>> fetchJSONData() async { var jsonResponse = await http.get(apiURL); if (jsonResponse.statusCode == 200) { final jsonItems = json.decode(jsonResponse.body).cast<Map<String, dynamic>>(); List<GetUsers> usersList = jsonItems.map<GetUsers>((json) { return GetUsers.fromJson(json); }).toList(); return usersList; } else { throw Exception('Failed to load data from internet'); } } |
9. Creating Widget build area in CustomJSONListView class. Now we would make the FutureBuilder widget which creates the widget based on newly come snapshot data. Now first we would check if the snapshot is empty or not than hide the CircularProgressIndicator() widget and display the ListView. We are using ListTile widget in ListView widget for displaying data with leading Circular avatar based text.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('JSON ListView in Flutter'), ), body: FutureBuilder<List<GetUsers>>( future: fetchJSONData(), builder: (context, snapshot) { if (!snapshot.hasData) return Center(child: CircularProgressIndicator()); return ListView( children: snapshot.data .map((user) => ListTile( title: Text(user.name), onTap: (){ print(user.name); }, subtitle: Text(user.phoneNumber), leading: CircleAvatar( backgroundColor: Colors.green, child: Text(user.name[0], style: TextStyle( color: Colors.white, fontSize: 20.0, )), ), ), ) .toList(), ); }, ), ); } |
10. Complete source code for main.dart file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
import 'package:flutter/material.dart'; import 'dart:convert'; import 'package:http/http.dart' as http; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: Center( child: JSONListView() ), )); } } class GetUsers { int id; String name; String email; String phoneNumber; GetUsers({ this.id, this.name, this.email, this.phoneNumber }); factory GetUsers.fromJson(Map<String, dynamic> json) { return GetUsers( id: json['id'], name: json['name'], email: json['email'], phoneNumber: json['phone'] ); } } class JSONListView extends StatefulWidget { CustomJSONListView createState() => CustomJSONListView(); } class CustomJSONListView extends State { final String apiURL = 'https://jsonplaceholder.typicode.com/users'; Future<List<GetUsers>> fetchJSONData() async { var jsonResponse = await http.get(apiURL); if (jsonResponse.statusCode == 200) { final jsonItems = json.decode(jsonResponse.body).cast<Map<String, dynamic>>(); List<GetUsers> usersList = jsonItems.map<GetUsers>((json) { return GetUsers.fromJson(json); }).toList(); return usersList; } else { throw Exception('Failed to load data from internet'); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('JSON ListView in Flutter'), ), body: FutureBuilder<List<GetUsers>>( future: fetchJSONData(), builder: (context, snapshot) { if (!snapshot.hasData) return Center(child: CircularProgressIndicator()); return ListView( children: snapshot.data .map((user) => ListTile( title: Text(user.name), onTap: (){ print(user.name); }, subtitle: Text(user.phoneNumber), leading: CircleAvatar( backgroundColor: Colors.green, child: Text(user.name[0], style: TextStyle( color: Colors.white, fontSize: 20.0, )), ), ), ) .toList(), ); }, ), ); } } |
Screenshots:
Awesome post! Keep up the great work! 🙂
good article,
How to get Street data.
thank you
Welcome 🙂 .