In flutter we would use TextField widget to get any type of typed input from application user. But without storing or processing this data, There is no use of the information. Basically we would store our data on online server where we have to host our own database. In this case we are using MySQL database which is one of the oldest and popular database among developers. We are using PHP(Hyper text processor) scripting language on our hosting server to insert text input textfield data to MySQL server. So what we basically doing in this project is we would get some values from app user from TextField widget and send the data to server using http.dart library. On server we are using PHP to receive the sent data into JSON format and insert all the data into MySQL database. Then simply print a success message on screen using Echo as response and show the response message in mobile application. So the app user will sure that all the data is successfully inserted. So in this tutorial we would Create Flutter Insert Text Input TextField data to MySQL Server iOS Android Example Tutorial.
Contents in this project Flutter Insert Text Input TextField data to MySQL Server iOS Android Example Tutorial:
1. Create MySQL Database & Table in PhpMyAdmin:
1. Before getting started to coding we have to manually create a new MySQL database or select an existing one to create table, So create a new db or select one like i did.
3. Create 4 columns inside the table named as id, name, email, phone_number. Id should be in integer data type, name, email and phone_number is in Varchar data type with 255 Length. We have to make the id field as Primary key with Auto increment like i did in below screenshot. Hit the Save button after done making changes.
4. Below is the screenshot of our user_info table after successfully creating.
2. Creating PHP Script to Receive Sent JSON data from App and Insert into MySQL db:
1. Create a .php extension file named as submit_data.php . You have to copy and paste all the below code in this 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 |
<?php //Define your Server host name here. $HostName = "localhost"; //Define your MySQL Database Name here. $DatabaseName = "id11189654_flutter_db"; //Define your Database User Name here. $HostUser = "id11189654_root"; //Define your Database Password here. $HostPass = "1234567890"; // Creating MySQL connection. $con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName); // Storing the received JSON in $json. $json = file_get_contents('php://input'); // Decode the received JSON and store into $obj $obj = json_decode($json,true); // Getting name from $obj. $name = $obj['name']; // Getting email from $obj. $email = $obj['email']; // Getting phone number from $obj. $phone_number = $obj['phone_number']; // Creating SQL query and insert the record into MySQL database table. $Sql_Query = "insert into user_info (name,email,phone_number) values ('$name','$email','$phone_number')"; if(mysqli_query($con,$Sql_Query)){ // On query success it will print below message. $MSG = 'Data Successfully Submitted.' ; // Converting the message into JSON format. $json = json_encode($MSG); // Echo the message. echo $json ; } else{ echo 'Try Again'; } mysqli_close($con); ?> |
2. We have to upload this file to our online hosting server. In this case i have a testing demo website named as https://flutter-examples.000webhostapp.com/ . We would upload the submit_data.php file to our server using file manager FTP. After uploading the file to server our complete path would be https://flutter-examples.000webhostapp.com/submit_data.php . We would use this URL in our flutter application.
3. Setting up http.dart Package for Flutter Project:
1. As we all know http.dart file is used to create connection between flutter app and online server. The http.dart package contains all the useful functions to transfer data between Clint and Server. We have to manually configure this package in our Flutter project. So open your project’s pubspec.yaml file present in your flutter project.
2. 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 |
Complete 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. Now we have to open our Flutter Project root folder in Terminal or CMD and execute flutter pub get command.
Now our project is configured successfully with http.dart package. Next step is 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. Call our main MyApp class using void main runApp() method.
1 |
void main() => runApp(MyApp()); |
3. Create our main MyApp class extends StatelessWidget. This is our main layout class. In this class we would call the TransfterData() 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('Insert TextField Data to MySQL Database')), body: Center( child: TransfterData() ) ) ); } } |
4. Create a class named as TransfterData(). In this class we would call our next main class TransfterDataWidget with createState() method. This method would allow mutable state management in given class root tree.
1 2 3 4 5 |
class TransfterData extends StatefulWidget { TransfterDataWidget createState() => TransfterDataWidget(); } |
5. Create our main class named as TransfterDataWidget extends with State full widget. In this class we would define all the widgets and perform web call.
1 2 3 4 |
class TransfterDataWidget extends State { } |
6. Create 3 Text Field controller named as nameController, emailController and phoneNumberController using TextEditingController() method. Using this controller we can get the entered value in TextField widget.
1 2 3 4 |
// Getting value from TextField widget. final nameController = TextEditingController(); final emailController = TextEditingController(); final phoneNumberController = TextEditingController(); |
7. Creating Boolean variable to show and hide the Circular progress indicator widget.
1 2 |
// Boolean variable for CircularProgressIndicator. bool visible = false ; |
8. Create a function named as webCall() in TransfterDataWidget class. In this class we would send the text input data to online server. In this function we would first get the values from TextField widget and showing a Alert dialog message after successfully done the API web call.
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 |
Future webCall() async{ // Showing CircularProgressIndicator using State. setState(() { visible = true ; }); // Getting value from Controller String name = nameController.text; String email = emailController.text; String phoneNumber = phoneNumberController.text; // API URL var url = 'https://flutter-examples.000webhostapp.com/submit_data.php'; // Store all data with Param Name. var data = {'name': name, 'email': email, 'phone_number' : phoneNumber}; // Starting Web Call with data. var response = await http.post(url, body: json.encode(data)); // Getting Server response into variable. var message = jsonDecode(response.body); // If Web call Success than Hide the CircularProgressIndicator. if(response.statusCode == 200){ setState(() { visible = false; }); } // Showing Alert Dialog with Response JSON. showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: new Text(message), actions: <Widget>[ FlatButton( child: new Text("OK"), onPressed: () { Navigator.of(context).pop(); }, ), ], ); }, ); } |
9. Creating 3 TextField widgets, 1 Raised button widget and 1 CircularProgressIndicator widget in Widget build area in TransfterDataWidget class. We would call the webCall() method on button onPress event.
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 |
Widget build(BuildContext context) { return Scaffold( body: SingleChildScrollView( child: Center( child: Column( children: <Widget>[ Padding( padding: const EdgeInsets.all(12.0), child: Text('Fill All Information in Form', style: TextStyle(fontSize: 22))), Container( width: 280, padding: EdgeInsets.all(10.0), child: TextField( controller: nameController, autocorrect: true, decoration: InputDecoration(hintText: 'Enter Name Here'), ) ), Container( width: 280, padding: EdgeInsets.all(10.0), child: TextField( controller: emailController, autocorrect: true, decoration: InputDecoration(hintText: 'Enter Email Here'), ) ), Container( width: 280, padding: EdgeInsets.all(10.0), child: TextField( controller: phoneNumberController, autocorrect: true, decoration: InputDecoration(hintText: 'Enter Phone Number Here'), ) ), RaisedButton( onPressed: webCall, color: Colors.pink, textColor: Colors.white, padding: EdgeInsets.fromLTRB(8, 8, 8, 8), child: Text('Click Here To Submit Data To Server'), ), Visibility( visible: visible, child: Container( margin: EdgeInsets.only(bottom: 30), child: CircularProgressIndicator() ) ), ], ), ))); } |
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 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 149 150 151 |
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('Insert TextField Data to MySQL Database')), body: Center( child: TransfterData() ) ) ); } } class TransfterData extends StatefulWidget { TransfterDataWidget createState() => TransfterDataWidget(); } class TransfterDataWidget extends State { // Getting value from TextField widget. final nameController = TextEditingController(); final emailController = TextEditingController(); final phoneNumberController = TextEditingController(); // Boolean variable for CircularProgressIndicator. bool visible = false ; Future webCall() async{ // Showing CircularProgressIndicator using State. setState(() { visible = true ; }); // Getting value from Controller String name = nameController.text; String email = emailController.text; String phoneNumber = phoneNumberController.text; // API URL var url = 'https://flutter-examples.000webhostapp.com/submit_data.php'; // Store all data with Param Name. var data = {'name': name, 'email': email, 'phone_number' : phoneNumber}; // Starting Web Call with data. var response = await http.post(url, body: json.encode(data)); // Getting Server response into variable. var message = jsonDecode(response.body); // If Web call Success than Hide the CircularProgressIndicator. if(response.statusCode == 200){ setState(() { visible = false; }); } // Showing Alert Dialog with Response JSON. showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: new Text(message), actions: <Widget>[ FlatButton( child: new Text("OK"), onPressed: () { Navigator.of(context).pop(); }, ), ], ); }, ); } @override Widget build(BuildContext context) { return Scaffold( body: SingleChildScrollView( child: Center( child: Column( children: <Widget>[ Padding( padding: const EdgeInsets.all(12.0), child: Text('Fill All Information in Form', style: TextStyle(fontSize: 22))), Container( width: 280, padding: EdgeInsets.all(10.0), child: TextField( controller: nameController, autocorrect: true, decoration: InputDecoration(hintText: 'Enter Name Here'), ) ), Container( width: 280, padding: EdgeInsets.all(10.0), child: TextField( controller: emailController, autocorrect: true, decoration: InputDecoration(hintText: 'Enter Email Here'), ) ), Container( width: 280, padding: EdgeInsets.all(10.0), child: TextField( controller: phoneNumberController, autocorrect: true, decoration: InputDecoration(hintText: 'Enter Phone Number Here'), ) ), RaisedButton( onPressed: webCall, color: Colors.pink, textColor: Colors.white, padding: EdgeInsets.fromLTRB(8, 8, 8, 8), child: Text('Click Here To Submit Data To Server'), ), Visibility( visible: visible, child: Container( margin: EdgeInsets.only(bottom: 30), child: CircularProgressIndicator() ) ), ], ), ))); } } |
Screenshots:
asmanamaji’s server IP address could not be found.
Asma the URL is working correctly .
ha sir but data not store in database.showing on terminal only..
Asma Jo data variable jisme hum name,email, phone number pass kar rhe h uske sath single cot me ‘name’ h vo sab ke sab php file me same hone chahie.
Hai actually mera pgm main problem jo mai insert kareso data quickely nai store hora database server par … plz suggest me.
Thank you soo much ..sir its work properly.
Welcome Asma 🙂 .
how to call api in this pgm tell me sir.
Asma the PHP file should be uploaded on my server then i am using the https://flutter-examples.000webhostapp.com/submit_data.php URL to insert data.
can you help me to know what’s my host name and host password and my host user on 000webhost.com ??
You can find the host name, host password and host user. First select your website in 000webhost panel -> Tools -> Database manager.
<?php
$hostname = "localhost";
$dbname = "id13512659_greengrocery";
$user = "id13512659_greengrocer";
$hostpassword = "zHc/@wlcI)7jG80W";
$connect=new mysqli($hostname,$user,$hostpassword,$dbname);
if($connect)
{
echo "connect";
}
else
{
echo "failed to connect to mysql";
exit();
}
hey i have written this code in connection.php just to connect but whenever i checked in website it shows page not found
hey i have solved this problem but can you please teach me how to insert the radio button value in mysql. I really need your help
Like the other values . I will make a tutorial on this particular topic 🙂 .
And also i am getting format exception error in jsonDecode. How can i solve that?
Did you add the http library in your project ?
On which platform you are testing your app ? Like local or online ?
Thank you for the reply. Yes like other one and Hope you will make soon. I really need it fast.
Dear
I can’t use it in my own server 🙁
msi-dz.com
Thank you so much
not working and showing int can not be cast to string error
Prakruti it is showing the error because our demo site is expired. If you test the code on your sever it should work .