JSON also known as Java Script Object Notation is one of the famous text based data exchange format used to process structured data. JSON is mostly used to transfer or exchange data between server and mobile applications. It is also one of the safest way to transfer data between two points. Flutter supports JSON data exchange using HTTP libraries. In this tutorial we would Create JSON Parsing ListView in Flutter Android iOS App Example Tutorial. I am creating JSON by myself using MySQL data and to convert MySQL data i am using PHP scripting language. So let’s get started 🙂 .
Contents in this project Create JSON Parsing ListView in Flutter Android iOS Example Tutorial:
1. Creating MySQL database & MySQL Table:
1. Open your hosting server and create a New MySQL database or select existing one in PhpMyAdmin like i did in below screenshot.
3. We have to create Table with 2 columns in our Table id and fruit_name. The id data type is int and fruit_name data type id Varchar. Id should be set as Auto Increment and Length of both columns is 255. Hit the Save button to create new table with defined columns.
4. After done creating table we have to enter some data in the Table. To enter data manually in table we have to open the Insert button present on PhpMyAdmin screen.
5. Now i am entering some Fruits names in fruits_name_table. Below is the list of Table after inserting fruit names.
Here you go guys, Now the Database and Table creation part is completed.
2. Creating PHP Script to Convert MySQL database data into JSON format:
1. Create a PHP extension file named as fruites_list_file.php and put all the below code inside it.
Source code for fruites_list_file.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 Fruits Table. $sql = "SELECT * FROM fruits_name_table"; $result = $conn->query($sql); if ($result->num_rows >0) { while($row[] = $result->fetch_assoc()) { $item = $row; $json = json_encode($item); } } else { echo "No Data Found."; } echo $json; $conn->close(); ?> |
2. We have to upload this file on our hosting server. In my case i am using free hosting platform for testing purpose. The web hosting should also have to connect with Domain name. Here i am using free sub-domain name. My sub domain name is flutter-examples.000webhostapp.com  . After uploading file to our server the File path is https://flutter-examples.000webhostapp.com/fruites_list_file.php . If you execute this URL in your web browser the result should look like below screenshot. This file would print all the data in JSON format in browser window.
3. Setup http.dart file for Flutter project:
1. The http.dart file is our main file. This file contain all the useful class and function resources to retrieve data between server and mobile app. We have to manually configure http.dart file for our project. So open your project’s pubspec.yaml file present in your flutter project.
2. Now open the pubspec.yaml file in any code editor and find dependencies. Put http: ^0.12.0 in next line.
1 2 3 4 |
dependencies: http: ^0.12.0 flutter: sdk: flutter |
Source code of my 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. Open flutter project in Terminal our Command Prompt and execute flutter pub get command.
4. After executing above command it will automatically download and configure http package in your flutter project.
Here you go now all the configuration part is completed next step is to start coding.
4. Start coding for App:
1. Open your project’s main.dart file and import material.dart package, convert package and http.dart package.
1 2 3 |
import 'package:flutter/material.dart'; import 'dart:convert'; import 'package:http/http.dart' as http; |
2. Call our main MyApp class using void main runApp() method.
1 |
void main() => runApp(MyApp()); |
3. Create our main MyApp class extends with StatelessWidget. This is our main calling class. We are calling JsonListView() class directly here which we would create in next step.
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 in Flutter') ), body: JsonListView(), ), ); } } |
4. Create a new class named as Fruitdata. In this class we would define 2 Variables named as id and fName. We would use this class as data List in our project to manage received JSON data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Fruitdata { String id; String fName; Fruitdata({ this.id, this.fName, }); factory Fruitdata.fromJson(Map<String, dynamic> json) { return Fruitdata( id: json['id'], fName: json['fruit_name'], ); } } |
5. Create a class named as JsonListView extends StatefulWidget. We would define here our main data parsing class with createState() method. This method will enables states in given class.
1 2 3 4 5 |
class JsonListView extends StatefulWidget { JsonListViewWidget createState() => JsonListViewWidget(); } |
6. Create a class named as JsonListViewWidget extends with StatefulWidget. This is our main parsing class with ListView widget.
1 2 3 4 |
class JsonListViewWidget extends State<JsonListView> { } |
7. Create a String variable named as uri containing our HTTP URL in JsonListViewWidget class.
1 |
final String uri = 'https://flutter-examples.000webhostapp.com/fruites_list_file.php'; |
8. Create a ASYNC function named as fetchFruits() with our created Fruitdata class. In this class we would Parse the JSON from given url and returns in complete object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
Future<List<Fruitdata>> fetchFruits() async { var response = await http.get(uri); if (response.statusCode == 200) { final items = json.decode(response.body).cast<Map<String, dynamic>>(); List<Fruitdata> listOfFruits = items.map<Fruitdata>((json) { return Fruitdata.fromJson(json); }).toList(); return listOfFruits; } else { throw Exception('Failed to load data.'); } } |
9. Create ListView widget and CircularProgressIndicator() widget in Widget build area in JsonListViewWidget class. The loading indicator will automatically hides from the screen after JSON loading completed. We are using MAP method to set data in ListView.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
Widget build(BuildContext context) { return FutureBuilder<List<Fruitdata>>( future: fetchFruits(), builder: (context, snapshot) { if (!snapshot.hasData) return Center( child: CircularProgressIndicator() ); return ListView( children: snapshot.data .map((data) => ListTile( title: Text(data.fName), onTap: (){print(data.fName);}, )) .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 |
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 in Flutter') ), body: JsonListView(), ), ); } } class Fruitdata { String id; String fName; Fruitdata({ this.id, this.fName, }); factory Fruitdata.fromJson(Map<String, dynamic> json) { return Fruitdata( id: json['id'], fName: json['fruit_name'], ); } } class JsonListView extends StatefulWidget { JsonListViewWidget createState() => JsonListViewWidget(); } class JsonListViewWidget extends State<JsonListView> { final String uri = 'https://flutter-examples.000webhostapp.com/fruites_list_file.php'; Future<List<Fruitdata>> fetchFruits() async { var response = await http.get(uri); if (response.statusCode == 200) { final items = json.decode(response.body).cast<Map<String, dynamic>>(); List<Fruitdata> listOfFruits = items.map<Fruitdata>((json) { return Fruitdata.fromJson(json); }).toList(); return listOfFruits; } else { throw Exception('Failed to load data.'); } } @override Widget build(BuildContext context) { return FutureBuilder<List<Fruitdata>>( future: fetchFruits(), builder: (context, snapshot) { if (!snapshot.hasData) return Center( child: CircularProgressIndicator() ); return ListView( children: snapshot.data .map((data) => ListTile( title: Text(data.fName), onTap: (){print(data.fName);}, )) .toList(), ); }, ); } } |
Screenshots:
I am getting this error when i try to decode Json from mysql I/flutter (21531): FormatException: Unexpected character
(at character 1)
Activating Dart DevTools…
I/flutter (21531): …
On which platform you are testing the code like locally or online ?
I had a similar problem.In your DB there are some tablea that are not in the utf-8 format but in latin.That is causing the json to fail.In php try converting the jsonencode($string,latinconvert-utf8);
Not the exact code but something like that.