Connecting Flutter with MySQL on Localhost and Online

Flutter is an increasingly popular framework for mobile app development, continuously improved by Google. One important aspect of app development is database connectivity. In this article, we will discuss how to connect Flutter with MySQL, both on a local computer (localhost) and on an online server, so you can store and retrieve data efficiently.

Before we begin, make sure you have Flutter installed and a new project created. If you want to use localhost, install XAMPP or MAMP to set up your MySQL server. For an online server, choose a hosting provider that supports MySQL.

Also, ensure that you have created a folder named img in your project or hosting directory and added images like sepatu.jpg and kemeja.jpg, as the MySQL data contains 2 entries: “sepatu” (shoes) and “kemeja” (shirt). The images for shoes and shirts are up to you.

I. Connecting Flutter with MySQL on Localhost

1.Creating the Database and Table in MySQL

First, activate XAMPP, then start Apache and MySQL. Next, create a database in phpMyAdmin named db_shop using the command:

CREATE TABLE `product` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nama` varchar(50) NOT NULL,
`photo` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8

Then, create a table called product using the following SQL command:

INSERT INTO `product` (`id`, `nama`, `photo`) VALUES
(1, ‘sepatu’, ‘sepatu.jpg’),
(2, ‘kemeja’, ‘kemeja.jpg’);

 

 

 

 

 

 

2.Creating the Database Connection File

In the htdocs folder, create a new folder named apiflutter and create a file named config.php.

Inside config.php, add the following code:

<?php
$conn = new mysqli("localhost", "root", "", "db_shop");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $sql = "SELECT * FROM product";
    $result = $conn->query($sql);
    $users = array();

    while($row = $result->fetch_assoc()) {
        $users[] = $row;
    }
    echo json_encode($users);
} 

$conn->close();
?>

Now, open this file in your browser with the URL http://localhost/apiflutter/config.php. If everything works, you will see the data displayed in JSON format.

 

3. Creating a New Flutter Project

Open VS Code, open the terminal, and navigate to the directory where you want to create the project. For example, D:\FLUTTER\ (adjust according to your setup). Once inside the directory, run the following command to create a new Flutter project: flutter create koneksikelokal

Wait for the project creation process to finish.

To connect Flutter with MySQL, you’ll need to use the http package to send API requests. Add the following dependency to your pubspec.yaml file:

dependencies:
http: ^0.13.3

Open main.dart in the lib folder and replace the code with the following:

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: UserPage(),
    );
  }
}

class UserPage extends StatefulWidget {
  @override
  _UserPageState createState() => _UserPageState();
}

class _UserPageState extends State<UserPage> {
  List productdata = [];

  @override
  void initState() {
    super.initState();
    fetchUsers();
  }

  Future<void> fetchUsers() async {
    final response =
        await http.get(Uri.parse('http://192.168.18.81/apiflutter/config.php'));
    if (response.statusCode == 200) {
      setState(() {
        productdata = json.decode(response.body);
      });
    } else {
      throw Exception('Failed to load users');
    }
  }

  Future<void> addUser(String nama, String photo) async {
    final response = await http.post(
      Uri.parse('http://192.168.18.81/apiflutter/config.php'),
      body: {'name': nama, 'email': photo},
    );
    if (response.statusCode == 200) {
      fetchUsers(); // Refresh user list
    } else {
      throw Exception('Failed to add user');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Product')),
      body: Column(
        children: [
          Container(
            color: Colors.grey,
            height: 30,
            child: Expanded(
                child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Container(
                  width: 100,
                  height: 20,
                  child: Center(
                    child: Text('NAMA'),
                  ),
                ),
                Container(
                    width: 100,
                    height: 20,
                    child: Center(
                      child: Text('PHOTO'),
                    )),
              ],
            )),
          ),
          Expanded(
            child: ListView.builder(
              itemCount: productdata.length,
              itemBuilder: (context, index) {
                return Padding(
                    padding: const EdgeInsets.symmetric(vertical: 8.0),
                    child: Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            SizedBox(
                              width: 100,
                              height: 50,
                              child: Center(
                                child: Text(productdata[index]['nama']),
                              ),
                            ),
                            SizedBox(
                              width: 100,
                              height: 50,
                              child: Center(
                                child: Image.network(
                                  'http://192.168.18.81/apiflutter/img/' +
                                      productdata[index][
                                          'photo'], // Ganti ID sesuai gambar yang diinginkan
                                  loadingBuilder:
                                      (context, child, loadingProgress) {
                                    if (loadingProgress == null) {
                                      return child; // Jika gambar sudah selesai dimuat
                                    } else {
                                      return Center(
                                        child: CircularProgressIndicator(
                                          value: loadingProgress
                                                      .expectedTotalBytes !=
                                                  null
                                              ? loadingProgress
                                                      .cumulativeBytesLoaded /
                                                  (loadingProgress
                                                          .expectedTotalBytes ??
                                                      1)
                                              : null,
                                        ),
                                      );
                                    }
                                  },
                                  errorBuilder: (context, error, stackTrace) {
                                    return Center(
                                        child: Text('Error loading image'));
                                  },
                                ),
                              ),
                            ),
                          ],
                        )
                      ],
                    ));
              },
            ),
          ),
        ],
      ),
    );
  }
}

Save the file and then run the app by clicking Run > Start Debugging. If successful, you will see the product data and images displayed on your app.

 

II. Connecting Flutter with MySQL on an Online Server or Hosting

 

1. Creating the Database and Table on MySQL Hosting

Log in to your hosting control panel (e.g., cPanel) and create a new database and user with the appropriate password. Then, open phpMyAdmin to create the product table using the following SQL:

CREATE TABLE `product` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nama` varchar(50) NOT NULL,
`photo` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8

Then, add the two products to the table using:

INSERT INTO `product` (`id`, `nama`, `photo`) VALUES
(1, ‘sepatu’, ‘sepatu.jpg’),
(2, ‘kemeja’, ‘kemeja.jpg’);

2. Create the config.php File

Create the config.php file inside the public_html folder. This file will handle the MySQL database connection.

NOTE :

  • root change with the user name of database
  • password_user change with the password of user database
  • db_shop change with the name of database

 

<?php
$conn = new mysqli(“localhost”, “root”, “password_user”, “db_shop”);

if ($conn->connect_error) {
die(“Connection failed: ” . $conn->connect_error);
}

header(‘Content-Type: application/json’);

if ($_SERVER[‘REQUEST_METHOD’] === ‘GET’) {
$sql = “SELECT * FROM product”;
$result = $conn->query($sql);
$users = array();

while($row = $result->fetch_assoc()) {
$users[] = $row;
}
echo json_encode($users);
}

$conn->close();
?>

Access this file in your browser with http://your_domain.com/config.php to see the data in JSON format.

 

3.Create a New Flutter Project

Create a new Flutter project using the terminal as explained earlier. Add the http package to the pubspec.yaml file, then replace the main.dart content with the code as shown above.

Note:

  • Replace your_domain.com with your actual domain.
  • Create an img folder in public_html and upload the sepatu.jpg and kemeja.jpg images as per the product data.

After running the app, you should see the product data and images from your online server.

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: UserPage(),
    );
  }
}

class UserPage extends StatefulWidget {
  @override
  _UserPageState createState() => _UserPageState();
}

class _UserPageState extends State<UserPage> {
  List productdata = [];

  @override
  void initState() {
    super.initState();
    fetchUsers();
  }

  Future<void> fetchUsers() async {
    final response =
        await http.get(Uri.parse('http://nama_domainku/config.php'));
    if (response.statusCode == 200) {
      setState(() {
        productdata = json.decode(response.body);
      });
    } else {
      throw Exception('Failed to load users');
    }
  }

  Future<void> addUser(String nama, String photo) async {
    final response = await http.post(
      Uri.parse('http://nama_domainku.com/config.php'),
      body: {'name': nama, 'email': photo},
    );
    if (response.statusCode == 200) {
      fetchUsers(); // Refresh user list
    } else {
      throw Exception('Failed to add user');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Product')),
      body: Column(
        children: [
          Container(
            color: Colors.grey,
            height: 30,
            child: Expanded(
                child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Container(
                  width: 100,
                  height: 20,
                  child: Center(
                    child: Text('NAMA'),
                  ),
                ),
                Container(
                    width: 100,
                    height: 20,
                    child: Center(
                      child: Text('PHOTO'),
                    )),
              ],
            )),
          ),
          Expanded(
            child: ListView.builder(
              itemCount: productdata.length,
              itemBuilder: (context, index) {
                return Padding(
                    padding: const EdgeInsets.symmetric(vertical: 8.0),
                    child: Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            SizedBox(
                              width: 100,
                              height: 50,
                              child: Center(
                                child: Text(productdata[index]['nama']),
                              ),
                            ),
                            SizedBox(
                              width: 100,
                              height: 50,
                              child: Center(
                                child: Image.network(
                                  'http://nama_domainku.com/img/' +
                                      productdata[index][
                                          'photo'], // Ganti ID sesuai gambar yang diinginkan
                                  loadingBuilder:
                                      (context, child, loadingProgress) {
                                    if (loadingProgress == null) {
                                      return child; // Jika gambar sudah selesai dimuat
                                    } else {
                                      return Center(
                                        child: CircularProgressIndicator(
                                          value: loadingProgress
                                                      .expectedTotalBytes !=
                                                  null
                                              ? loadingProgress
                                                      .cumulativeBytesLoaded /
                                                  (loadingProgress
                                                          .expectedTotalBytes ??
                                                      1)
                                              : null,
                                        ),
                                      );
                                    }
                                  },
                                  errorBuilder: (context, error, stackTrace) {
                                    return Center(
                                        child: Text('Error loading image'));
                                  },
                                ),
                              ),
                            ),
                          ],
                        )
                      ],
                    ));
              },
            ),
          ),
        ],
      ),
    );
  }
}

if successful it will look like the picture :

 

Conclusion

Connecting Flutter with MySQL, both locally and on an online server, involves clear steps. By using a PHP-based API, you can easily manage your data and present it in your Flutter application. By following this guide, you now have a strong foundation to develop more complex data-driven applications.

Leave a Reply

Your email address will not be published. Required fields are marked *