JSON ListView with images and text is most commonly used in all mobile applications. We have seen so much apps in our life like social media apps, online e-kart apps like Flipkart, Amazon etc. They all will show us the data in multiple images and Text forms. The data is categorized in multiple choices but shows in vertical ListView format. The data is directly coming from online server using a API URL and we would parse the JSON in our flutter app. After done parsing data we would shows all the JSON data in ListView. So in this tutorial we would Create Flutter Custom JSON ListView with Images & Text in Android iOS Example Tutorial.
Contents in this project Flutter Custom JSON ListView with Images & Text Android iOS Example Tutorial:
1. Creating MySQL Database and Table:
1. I am showing images directly from my own sub-domain web hosting server. So all the image is stored in my hosting panel. My hosting panel supports PHP web hosting and has MySQL database. To manage MySQL database we have to use PhpMyAdmin control panel. I am using MySQL database in my current tutorial. So open your hosting control panel and locate to PhpMyAdmin control panel. You could select already created MySQL database or create a new database like i did in below screenshot.
3. We have to create 3 Columns in table named as id, flower_name and flower_image_url. The id datatype should be in integer and and flower name and flower image url should be in Varchar datatype. One more thing the id should be set as Auto Increment with Primary key. After done setting up hit the Save button.
4. Table structure should look like below screenshot after done saving.
5. Now i am uploading few image on my domain hosting server and Storing the Image complete URL with Image name in MySQL database table manually. Screenshot of Table after entering records.
2. Creating PHP Script to Convert all flowers name and flowers URL in JSON format:
1. We have to create a .php extension file named as getFlowersList.php .
Complete source code for getFlowersList.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 45 |
<?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 Flowers Table. $sql = "SELECT * FROM Flowers_Name_List"; $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 are uploading getFlowersList.php file on our hosting server web space. Our hosting space is connected with a sub-domain name flutter-examples.000webhostapp.com . After uploading the file on server complete file path is https://flutter-examples.000webhostapp.com/getFlowersList.php . If you execute the URL in your web browser window the you will see the complete JSON like below screenshot. We will use this URL in our flutter project.
3. Setting up http.dart package for Flutter Project:
1. The http.dart package is one of the most usable package file for flutter applications. http package is used to send data between online hosting server and client. The http.dart package did not come inbuilt with flutter project so we have to manually configure the package for our server. So open your project’s pubspec.yaml file present in your project’s root folder.
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 done saving file, We have to open our flutter project folder in Command Prompt or Terminal and execute flutter pub get command. This command will download the newly added packages in flutter project.
Here you go now all the configuration part is done. It’s time to start coding for app.
4. Start Coding for Flutter 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 MyApp class here.
1 |
void main() => runApp(MyApp()); |
3. Create our main Root view class named as MyApp extends StatelessWidget. In this class we would call the JsonImageList() 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 Images & Text') ), body: JsonImageList(), ), ); } } |
4. Create a class named as Flowerdata. In this class we would create 3 variable named as id, flowerName and flowerImageURL. The id variable should be integer type and other two variables is in String type. This class is used to extract data from JSON data one by one for JSON parsing purpose. The object values should be same as the JSON items name to populate them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Flowerdata { int id; String flowerName; String flowerImageURL; Flowerdata({ this.id, this.flowerName, this.flowerImageURL }); factory Flowerdata.fromJson(Map<String, dynamic> json) { return Flowerdata( id: json['id'], flowerName: json['flower_name'], flowerImageURL: json['flower_image_url'] ); } } |
5. Create a class named as JsonImageList extends StatefulWidget. In this class we would create the createState() method with our main ListView class. This method would enable the mutable state management in given class tree.
1 2 3 4 5 |
class JsonImageList extends StatefulWidget { JsonImageListWidget createState() => JsonImageListWidget(); } |
6. Create another class named as JsonImageListWidget extends State. This would be our main Widget ListView class.
1 2 3 4 |
class JsonImageListWidget extends State { } |
7. Create a Sting variable named as apiURL and assign the API URL to it.
1 |
final String apiURL = 'https://flutter-examples.000webhostapp.com/getFlowersList.php'; |
8. Create a Future function named as fetchFlowers() ASYNC function. This function is our main function in which we would parse the JSON using Flowerdata class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
Future<List<Flowerdata>> fetchFlowers() async { var response = await http.get(apiURL); if (response.statusCode == 200) { final items = json.decode(response.body).cast<Map<String, dynamic>>(); List<Flowerdata> listOfFruits = items.map<Flowerdata>((json) { return Flowerdata.fromJson(json); }).toList(); return listOfFruits; } else { throw Exception('Failed to load data from Server.'); } } |
9. Create a function named as selectedItem() with Context and holder parameter. This method will be called when user selects any ListView item and print the selected item in Alert dialog box.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
selectedItem(BuildContext context, String holder) { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: new Text(holder), actions: <Widget>[ FlatButton( child: new Text("OK"), onPressed: () { Navigator.of(context).pop(); }, ), ], ); }, ); } |
10. Creating Widget build are in JsonImageListWidget class. Inside the Widget build area we would first Show the CircularProgressIndicator() widget on data loading and hide the CircularProgressIndicator after done data loading. Now we would make the ListView widget and create the complete Item view . Inside the Item view we would put a Image and Text Widget. The Image widget is used to show the flower image and Text widget is used to show the flower name.
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 |
Widget build(BuildContext context) { return FutureBuilder<List<Flowerdata>>( future: fetchFlowers(), 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.flowerName);}, child: Row( children: [ Container( width: 200, height: 100, margin: EdgeInsets.fromLTRB(10, 0, 10, 0), child: ClipRRect( borderRadius: BorderRadius.circular(8.0), child: Image.network(data.flowerImageURL, width: 200, height: 100, fit: BoxFit.cover,))), Flexible(child: Text(data.flowerName, style: TextStyle(fontSize: 18))) ]),), 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 |
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 Images & Text') ), body: JsonImageList(), ), ); } } class Flowerdata { int id; String flowerName; String flowerImageURL; Flowerdata({ this.id, this.flowerName, this.flowerImageURL }); factory Flowerdata.fromJson(Map<String, dynamic> json) { return Flowerdata( id: json['id'], flowerName: json['flower_name'], flowerImageURL: json['flower_image_url'] ); } } class JsonImageList extends StatefulWidget { JsonImageListWidget createState() => JsonImageListWidget(); } class JsonImageListWidget extends State { final String apiURL = 'https://flutter-examples.000webhostapp.com/getFlowersList.php'; Future<List<Flowerdata>> fetchFlowers() async { var response = await http.get(apiURL); if (response.statusCode == 200) { final items = json.decode(response.body).cast<Map<String, dynamic>>(); List<Flowerdata> listOfFruits = items.map<Flowerdata>((json) { return Flowerdata.fromJson(json); }).toList(); return listOfFruits; } else { throw Exception('Failed to load data from Server.'); } } selectedItem(BuildContext context, String holder) { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: new Text(holder), actions: <Widget>[ FlatButton( child: new Text("OK"), onPressed: () { Navigator.of(context).pop(); }, ), ], ); }, ); } @override Widget build(BuildContext context) { return FutureBuilder<List<Flowerdata>>( future: fetchFlowers(), 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.flowerName);}, child: Row( children: [ Container( width: 200, height: 100, margin: EdgeInsets.fromLTRB(10, 0, 10, 0), child: ClipRRect( borderRadius: BorderRadius.circular(8.0), child: Image.network(data.flowerImageURL, width: 200, height: 100, fit: BoxFit.cover,))), Flexible(child: Text(data.flowerName, style: TextStyle(fontSize: 18))) ]),), Divider(color: Colors.black), ],)) .toList(), ); }, ); } } |
Screenshots:
hi, can you help if images are in BLOB
hello admin, can it build a code for image upload from users to mysql server with like this flutter and php code type?