In our previous tutorial we have created JSON ListView with Single type of single item but, In this tutorial we would create Flutter Custom JSON ListView with Multiple Text Items Example. All the items is coming directly from our online hosting + domain server. Where we have hosted MySQL database using PhpMyAdmin control panel. All the data is stored in MySQL database Table. We would make a API(Application Programming Interface) using PHP scripting language which would convert all the MySQL database data into JSON from. So let’s get started 🙂 .
Contents in this project Flutter Custom JSON ListView with Multiple Text Items Example Tutorial Android iOS:
1. Creating MySQL Database with Table :
1. I have a online sub-domain name connected with web hosting. In my hosting panel i have hosted MySQL database using PhpMyAdmin control panel. So first i’ll login into my PhpMyAdmin control panel and select my MySQL database or you can also create your new database.
3. There are 4 columns in our Table. id, student_name, student_phone_number and student_class. The id datatype should be set as integer and all the other three columns type is Varchar. The length should be 255 and id should be set as Primary Key with Auto Increment. Hit the Save button after making changes.
4. After done creating table the Table structure should look like below screenshot.
5. Now click on the Insert button to insert some records manually.
6. After done inserting records Table will look like below screenshot.
Now all the database creating part is done.
2. Creating PHP Script to Convert all the MySQL data into JSON :
1. Create a .PHP extension file named as getStudentInfo.php and paste all the below code inside it. You have to change the database name, database hostname, database username and database password of your own MySQL database.
Complete Source code for getStudentInfo.php 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 |
<?php //Define your host here. $HostName = "localhost"; //Define your MySQL Database Name here. $DatabaseName = "id11189654_flutter_db"; //Define your Database UserName here. $HostUser = "id11189654_root"; //Define your Database Password here. $HostPass = "1234567890"; // Creating connection $conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Creating SQL command to fetch all records from Student_Data Table. $sql = "SELECT * FROM Student_Data"; $result = $conn->query($sql); if ($result->num_rows >0) { while($row[] = $result->fetch_assoc()) { $item = $row; $json = json_encode($item, JSON_NUMERIC_CHECK); } } else { echo "No Data Found."; } echo $json; $conn->close(); ?> |
2. We have to upload getStudentInfo.php file on our online web-hosting panel using File Manger. I have a sub-domain named as flutter-examples.000webhostapp.com connected with Web-hosting space. After uploading file to our server the File path will be https://flutter-examples.000webhostapp.com/getStudentInfo.php . This would be our API URL we would use in flutter application. If we would run this URL in web browser then it will show us all the records in JSON format.
Screenshot of JSON:
3. Setting up http.dart package for Flutter Project:
1. We are using the http.dart package in our flutter project to receive data from server. We have to manually install this package in our flutter project. So open your Flutter Project folder and open pubspec.yaml file in any code editor.
2. Open the pubspec.yaml file in any code editor and find dependencies and Put http: ^0.12.0 in next line.
1 2 3 4 |
dependencies: http: ^0.12.0 flutter: sdk: flutter |
Complete Source code for pubspec.yaml file.
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 saving the file we have to open our Flutter Project root folder in Command Prompt or Terminal and execute flutter pub get command. This command would download the http library from online package server and install it.
Now our configuration part has done.
4. Start Coding for App:
1. Open your project’s main.dart file and import material.dart, convert and http.dart package.
1 2 3 |
import 'package:flutter/material.dart'; import 'dart:convert'; import 'package:http/http.dart' as http; |
2. Create void main runApp() method and call our main root MyApp class here.
1 |
void main() => runApp(MyApp()); |
3. Create a class named as MyApp extends with State less widget. This is our main Root view class. In this class we would call JsonListView() class.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('JSON ListView with Multiple Text Items') ), body: JsonListView(), ), ); } } |
4. Create a class named as Studentdata. In this class we would make 4 variable named as studentID, studentName, studentPhoneNumber and studentSubject. In this class we would populate the data from JSON so the argument must be same as Table columns. We would create the factory Studentdata.fromJson() method where we would populate the items.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class Studentdata { int studentID; String studentName; int studentPhoneNumber; String studentSubject; Studentdata({ this.studentID, this.studentName, this.studentPhoneNumber, this.studentSubject }); factory Studentdata.fromJson(Map<String, dynamic> json) { return Studentdata( studentID: json['id'], studentName: json['student_name'], studentPhoneNumber: json['student_phone_number'], studentSubject: json['student_class'] ); } } |
5. Create a class named as JsonListView extends StatefulWidget. In this class we would make the createState() method and pass the child class here. The createState() method would enable the mutable state in given class tree.
1 2 3 4 5 |
class JsonListView extends StatefulWidget { JsonListViewWidget createState() => JsonListViewWidget(); } |
6. Create a class named as JsonListViewWidget extends State. This would be our main child class.
1 2 3 4 |
class JsonListViewWidget extends State { } |
7. Create a String variable named as apiURL. Here we would assign the API URL in JsonListViewWidget class.
1 |
final String apiURL = 'https://flutter-examples.000webhostapp.com/getStudentInfo.php'; |
8. Create a Future function named as fetchStudents() in JsonListViewWidget class. In this class we would parse the JSON data with Studentdata class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
Future<List<Studentdata>> fetchStudents() async { var response = await http.get(apiURL); if (response.statusCode == 200) { final items = json.decode(response.body).cast<Map<String, dynamic>>(); List<Studentdata> studentList = items.map<Studentdata>((json) { return Studentdata.fromJson(json); }).toList(); return studentList; } else { throw Exception('Failed to load data from Server.'); } } |
9. Create another function named as selectedItem() with Context and String argument. Using this function we would print the Selected Item Student name on screen using Alert dialog message box.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
selectedItem(BuildContext context, String dataHolder) { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: new Text(dataHolder), actions: <Widget>[ FlatButton( child: new Text("OK"), onPressed: () { Navigator.of(context).pop(); }, ), ], ); }, ); } |
10. Create widget build area in Studentdata class. Here we would create the CircularProgressIndicator() widget with ListView widget. Inside the ListView widget we would make a GestureDetector() widget and put 4 Text views as child in it.
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 FutureBuilder<List<Studentdata>>( future: fetchStudents(), builder: (context, snapshot) { if (!snapshot.hasData) return Center( child: CircularProgressIndicator() ); return ListView( children: snapshot.data .map((data) => Column(children: <Widget>[ GestureDetector( onTap: (){selectedItem(context, data.studentName);}, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: EdgeInsets.fromLTRB(0, 20, 0, 20), child: Text('ID = ' + data.studentID.toString(), style: TextStyle(fontSize: 21))), Padding( padding: EdgeInsets.fromLTRB(0, 0, 0, 20), child: Text('Name = ' + data.studentName, style: TextStyle(fontSize: 21))), Padding( padding: EdgeInsets.fromLTRB(0, 0, 0, 20), child: Text('Phone Number = ' + data.studentPhoneNumber.toString(), style: TextStyle(fontSize: 21))), Padding( padding: EdgeInsets.fromLTRB(0, 0, 0, 20), child: Text('Subject = ' + data.studentSubject, style: TextStyle(fontSize: 21))), ]),), Divider(color: Colors.black), ],)) .toList(), ); }, ); } |
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 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 |
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( appBar: AppBar( title: Text('JSON ListView with Multiple Text Items') ), body: JsonListView(), ), ); } } class Studentdata { int studentID; String studentName; int studentPhoneNumber; String studentSubject; Studentdata({ this.studentID, this.studentName, this.studentPhoneNumber, this.studentSubject }); factory Studentdata.fromJson(Map<String, dynamic> json) { return Studentdata( studentID: json['id'], studentName: json['student_name'], studentPhoneNumber: json['student_phone_number'], studentSubject: json['student_class'] ); } } class JsonListView extends StatefulWidget { JsonListViewWidget createState() => JsonListViewWidget(); } class JsonListViewWidget extends State { final String apiURL = 'https://flutter-examples.000webhostapp.com/getStudentInfo.php'; Future<List<Studentdata>> fetchStudents() async { var response = await http.get(apiURL); if (response.statusCode == 200) { final items = json.decode(response.body).cast<Map<String, dynamic>>(); List<Studentdata> studentList = items.map<Studentdata>((json) { return Studentdata.fromJson(json); }).toList(); return studentList; } else { throw Exception('Failed to load data from Server.'); } } selectedItem(BuildContext context, String dataHolder) { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: new Text(dataHolder), actions: <Widget>[ FlatButton( child: new Text("OK"), onPressed: () { Navigator.of(context).pop(); }, ), ], ); }, ); } @override Widget build(BuildContext context) { return FutureBuilder<List<Studentdata>>( future: fetchStudents(), builder: (context, snapshot) { if (!snapshot.hasData) return Center( child: CircularProgressIndicator() ); return ListView( children: snapshot.data .map((data) => Column(children: <Widget>[ GestureDetector( onTap: (){selectedItem(context, data.studentName);}, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: EdgeInsets.fromLTRB(0, 20, 0, 20), child: Text('ID = ' + data.studentID.toString(), style: TextStyle(fontSize: 21))), Padding( padding: EdgeInsets.fromLTRB(0, 0, 0, 20), child: Text('Name = ' + data.studentName, style: TextStyle(fontSize: 21))), Padding( padding: EdgeInsets.fromLTRB(0, 0, 0, 20), child: Text('Phone Number = ' + data.studentPhoneNumber.toString(), style: TextStyle(fontSize: 21))), Padding( padding: EdgeInsets.fromLTRB(0, 0, 0, 20), child: Text('Subject = ' + data.studentSubject, style: TextStyle(fontSize: 21))), ]),), Divider(color: Colors.black), ],)) .toList(), ); }, ); } } |
Screenshots:
Not working , Still taking loading progresss
Muzammil it is working correctly, I have just check the complete code and run into simulator and the data is loading.
it loads for long time only if there s an issue with ur backend…check error report and see if you are passing proper values..
I have tested and the code is working perfectly fine
I have run the code its gives me the black background and shows data in red color.
Munib API URL on this tutorial has expired, Maybe this is why it is showing us this error. Read my this tutorial this would help you : https://flutter-examples.com/flutter-http-pub-package/ .