Hello friends, It’s been so long since I had posted a tutorial on JSON in flutter. Friends as we all know if we start learning flutter and choose flutter as carrier then we must have to learn JSON parsing in flutter. Because in today’s world most of applications are dynamic and their content is coming directly from online server. Dynamic apps are easy to handle by their users because they can change any content inside the app using few clicks and typing. Therefore administrator does not need to contact the app developer every time when he wants to make any changes. So in flutter to Fetch and Parse JSON, a very handy library Pub package known as http 0.13.3 comes. Today most of flutter developers usages the http package. So today we would learn about Flutter HTTP Pub Package to Fetch Parse JSON ListView Example in Android iOS with CardView.
Content in this project Flutter HTTP Pub Package to Fetch Parse JSON ListView Example :-
1. First of all we have to install the HTTP package in our flutter application. So open your project’s main Root folder inside Command Prompt in windows and Terminal in MAC and execute below command.
1 |
flutter pub add http |
2. Now next step is to start coding for the app. So open your project’s main.dart file and import material.dart , dart:convert and http.dart package.
1 2 3 |
import 'package:flutter/material.dart'; import 'dart:convert'; import 'package:http/http.dart' as http; |
3. Creating void main runApp() method and here we would call our main parent MyApp class.
1 |
void main() => runApp(MyApp()); |
4. Creating our main MyApp extends StatelessWidget class. In this class we would call ListView_JSON class as its child.
1 2 3 4 5 6 7 8 9 |
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: Center(child: ListView_JSON()), )); } } |
5. Now we would make another stand alone class named as ParseJSON. We would use this class as a dynamic List to parse each item from JSON which we would fetch from server.
Note:- Please make sure here in the JSON – json[‘id’] , json[‘name’] , json[’email’] id, name and email should be same as our JSON object names.
1 2 3 4 5 6 7 8 9 10 11 |
class ParseJSON { int? id; String? name; String? email; ParseJSON({this.id, this.name, this.email}); factory ParseJSON.fromJson(Map<String, dynamic> json) { return ParseJSON(id: json['id'], name: json['name'], email: json['email']); } } |
6. Creating a class named as ListView_JSON extends StatefulWidget. In this class we would make CustomListTileView with createState() method to enable mutable state management in given class child.
1 2 3 |
class ListView_JSON extends StatefulWidget { CustomListTileView createState() => CustomListTileView(); } |
7. Creating our main Child CustomListTileView class extends State<ListView_JSON>.
1 2 3 4 5 |
class CustomListTileView extends State<ListView_JSON> { } |
8. Creating a String variable named as apiURL. We would give here the API URL.
1 |
final String apiURL = 'https://jsonplaceholder.typicode.com/users'; |
9. Creating a Future type of fetchJSON ASYNC method. In this function we would Fetch and Parse JSON.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Future<List<ParseJSON>> fetchJSON() async { var jsonResponse = await http.get(Uri.parse(apiURL)); if (jsonResponse.statusCode == 200) { final jsonItems = json.decode(jsonResponse.body).cast<Map<String, dynamic>>(); List<ParseJSON> tempList = jsonItems.map<ParseJSON>((json) { return ParseJSON.fromJson(json); }).toList(); return tempList; } else { throw Exception('Failed To Load Data'); } } |
10. Creating Widget Build area. Now we would here make a ListView widget with Card widget and put the ListTile widget inside it to make the Card View List View.
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 |
Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('JSON ListTile ListView in Flutter'), ), body: FutureBuilder<List<ParseJSON>>( future: fetchJSON(), builder: (context, data) { if (data.hasError) { return Center(child: Text("${data.error}")); } else if (data.hasData) { var items = data.data as List<ParseJSON>; return ListView.builder( itemCount: items == null ? 0 : items.length, itemBuilder: (context, index) { return Card( child: ListTile( title: Text( items[index].name.toString(), ), onTap: () { print( items[index].name.toString(), ); }, subtitle: Text( items[index].email.toString(), ), leading: CircleAvatar( backgroundColor: Colors.green, child: Text(items[index].name.toString()[0], style: TextStyle( color: Colors.white, fontSize: 21.0, )), ), )); }); } else { return Center( child: CircularProgressIndicator(), ); } }, ), ); } |
11. 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 |
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: ListView_JSON()), )); } } class ParseJSON { int? id; String? name; String? email; ParseJSON({this.id, this.name, this.email}); factory ParseJSON.fromJson(Map<String, dynamic> json) { return ParseJSON(id: json['id'], name: json['name'], email: json['email']); } } class ListView_JSON extends StatefulWidget { CustomListTileView createState() => CustomListTileView(); } class CustomListTileView extends State<ListView_JSON> { final String apiURL = 'https://jsonplaceholder.typicode.com/users'; Future<List<ParseJSON>> fetchJSON() async { var jsonResponse = await http.get(Uri.parse(apiURL)); if (jsonResponse.statusCode == 200) { final jsonItems = json.decode(jsonResponse.body).cast<Map<String, dynamic>>(); List<ParseJSON> tempList = jsonItems.map<ParseJSON>((json) { return ParseJSON.fromJson(json); }).toList(); return tempList; } else { throw Exception('Failed To Load Data'); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('JSON ListTile ListView in Flutter'), ), body: FutureBuilder<List<ParseJSON>>( future: fetchJSON(), builder: (context, data) { if (data.hasError) { return Center(child: Text("${data.error}")); } else if (data.hasData) { var items = data.data as List<ParseJSON>; return ListView.builder( itemCount: items == null ? 0 : items.length, itemBuilder: (context, index) { return Card( child: ListTile( title: Text( items[index].name.toString(), ), onTap: () { print( items[index].name.toString(), ); }, subtitle: Text( items[index].email.toString(), ), leading: CircleAvatar( backgroundColor: Colors.green, child: Text(items[index].name.toString()[0], style: TextStyle( color: Colors.white, fontSize: 21.0, )), ), )); }); } else { return Center( child: CircularProgressIndicator(), ); } }, ), ); } } |
Screenshots:-
And how would one move to the detail page of these posts?
perro you want to send the selected item to next screen then read my this tutorial this would help you :- https://flutter-examples.com/flutter-send-listview-selected-item/