Hello friends, It’s been few months since I had posted a tutorial regarding on JSON topic. So Here I come. Recently when I was seeing some of my old projects in Flutter, Then I saw It would be a good topic for beginners because you can learn 2 things together in this tutorial. First learn about parsing JSON another is Sending value from one screen to next screen. One more thing we’re using Jsonplaceholder fake JSON API for testing purpose in this tutorial. So in this tutorial we would learn about Flutter Show JSON ListView Selected Value to Next Activity Screen.
Contents in this project Flutter Show JSON ListView Selected Value to Next Activity Screen :-
1. First of all we have to install http 0.13.4 Pub package in our current flutter project. In order to use HTTP packages in our code. So open your flutter project Root directory in CMD or Terminal and execute below command.
1 |
flutter pub add http |
2. Now we’re ready to roll on. 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 Root parent class MyApp.
1 |
void main() => runApp(MyApp()); |
4. Creating MyApp class and in this class we would call our App class.
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: App()), )); } } |
5. Now we would pause the further coding and make our main Object class. The main purpose of this class is to parse JSON values like id, name and email from JSON object to a list string.
1 2 3 4 5 6 7 8 9 10 11 |
class Object { int? id; String? name; String? email; Object({this.id, this.name, this.email}); factory Object.fromJson(Map<String, dynamic> json) { return Object(id: json['id'], name: json['name'], email: json['email']); } } |
6. Creating our main App extends StatefulWidget. In this class we would call Json_ListView class with createState() method to enable mutable State management in the given class tree.
1 2 3 |
class App extends StatefulWidget { Json_ListView createState() => Json_ListView(); } |
7. Cerating our main JSON List screen class named as Json_ListView. This is officially our first screen.
1 2 3 4 5 |
class Json_ListView extends State<App> { ] |
8. Creating a Future type of ASYNC function named as fetchJSON with our Object class. In this function we would simply extract the data like id, name and email from JSON coming from online URL and return it into Object form.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Future<List<Object>> fetchJSON() async { var jsonResponse = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/users')); if (jsonResponse.statusCode == 200) { final jsonItems = json.decode(jsonResponse.body).cast<Map<String, dynamic>>(); List<Object> tempList = jsonItems.map<Object>((json) { return Object.fromJson(json); }).toList(); return tempList; } else { throw Exception('Failed To Load Data...'); } } |
9. Creating another function named as getItemAndNavigate() with 3 arguments name, email and context of app. Now in this function what we do is, We would send all these items to the next activity screen with their object reference name. We would call this function on List item on Tap event.
1 2 3 4 5 6 7 |
getItemAndNavigate(String name, String email, BuildContext context) { Navigator.push( context, MaterialPageRoute( builder: (context) => SecondScreen(nameHolder: name, emailHolder: email))); } |
10. Creating Widget Build area -> Here we would make the FutureBuilder widget and call the fetchJSON function here and after parsing JSON show all the data into 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 |
Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('JSON ListView in Flutter'), ), body: FutureBuilder<List<Object>>( future: fetchJSON(), builder: (context, data) { if (data.hasError) { return Center(child: Text("${data.error}")); } else if (data.hasData) { var items = data.data as List<Object>; return ListView.builder( itemCount: items == null ? 0 : items.length, itemBuilder: (context, index) { return Card( child: ListTile( title: Text( items[index].name.toString(), ), onTap: () { getItemAndNavigate(items[index].name.toString(), items[index].email.toString(), context); }, subtitle: Text( items[index].email.toString(), ), leading: CircleAvatar( backgroundColor: Color.fromARGB(255, 242, 2, 250), child: Text(items[index].name.toString()[0], style: const TextStyle( color: Colors.white, fontSize: 22.0, )), ), )); }); } else { return const Center( child: CircularProgressIndicator(), ); } }, ), ); } |
11. Creating our next class named as SecondScreen. In this class we would simply receive the Send item from previous screen. One more important thing In previous class which object name we would use must be same in this class to receive the data.
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 |
class SecondScreen extends StatelessWidget { final nameHolder, emailHolder; const SecondScreen({Key? key, @required this.nameHolder, this.emailHolder}) : super(key: key); goBack(BuildContext context) { Navigator.pop(context); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Second Screen"), ), body: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Center( child: Text( 'Name = ' + nameHolder, style: const TextStyle(fontSize: 22), textAlign: TextAlign.center, )), Center( child: Text( 'Email = ' + emailHolder, style: const TextStyle(fontSize: 22), textAlign: TextAlign.center, )), RaisedButton( onPressed: () => goBack(context), color: Colors.lightBlue, textColor: Colors.white, child: const Text('Go Back To Previous Screen'), ) ])); } } |
12. 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 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 |
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: App()), )); } } class Object { int? id; String? name; String? email; Object({this.id, this.name, this.email}); factory Object.fromJson(Map<String, dynamic> json) { return Object(id: json['id'], name: json['name'], email: json['email']); } } class App extends StatefulWidget { Json_ListView createState() => Json_ListView(); } class Json_ListView extends State<App> { Future<List<Object>> fetchJSON() async { var jsonResponse = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/users')); if (jsonResponse.statusCode == 200) { final jsonItems = json.decode(jsonResponse.body).cast<Map<String, dynamic>>(); List<Object> tempList = jsonItems.map<Object>((json) { return Object.fromJson(json); }).toList(); return tempList; } else { throw Exception('Failed To Load Data...'); } } getItemAndNavigate(String name, String email, BuildContext context) { Navigator.push( context, MaterialPageRoute( builder: (context) => SecondScreen(nameHolder: name, emailHolder: email))); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('JSON ListView in Flutter'), ), body: FutureBuilder<List<Object>>( future: fetchJSON(), builder: (context, data) { if (data.hasError) { return Center(child: Text("${data.error}")); } else if (data.hasData) { var items = data.data as List<Object>; return ListView.builder( itemCount: items == null ? 0 : items.length, itemBuilder: (context, index) { return Card( child: ListTile( title: Text( items[index].name.toString(), ), onTap: () { getItemAndNavigate(items[index].name.toString(), items[index].email.toString(), context); }, subtitle: Text( items[index].email.toString(), ), leading: CircleAvatar( backgroundColor: Color.fromARGB(255, 242, 2, 250), child: Text(items[index].name.toString()[0], style: const TextStyle( color: Colors.white, fontSize: 22.0, )), ), )); }); } else { return const Center( child: CircularProgressIndicator(), ); } }, ), ); } } class SecondScreen extends StatelessWidget { final nameHolder, emailHolder; const SecondScreen({Key? key, @required this.nameHolder, this.emailHolder}) : super(key: key); goBack(BuildContext context) { Navigator.pop(context); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Second Screen"), ), body: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Center( child: Text( 'Name = ' + nameHolder, style: const TextStyle(fontSize: 22), textAlign: TextAlign.center, )), Center( child: Text( 'Email = ' + emailHolder, style: const TextStyle(fontSize: 22), textAlign: TextAlign.center, )), RaisedButton( onPressed: () => goBack(context), color: Colors.lightBlue, textColor: Colors.white, child: const Text('Go Back To Previous Screen'), ) ])); } } |
Screenshots :-