flutter mysql

Flutter and MySQL: A Comprehensive Guide

If you are looking to build a mobile app with a backend database, you might have heard about Flutter and MySQL. In this guide, we will explore the different ways to connect Flutter with MySQL and how to perform CRUD operations on the database.

What is Flutter?

Flutter is an open-source mobile application development framework created by Google. It allows developers to build high-performance, cross-platform mobile apps for iOS and Android using a single codebase. Flutter uses the Dart programming language and provides a rich set of pre-built widgets that can be used to create beautiful UIs.

What is MySQL?

MySQL is an open-source relational database management system. It is one of the most popular databases used for web applications due to its scalability, security, and ease of use. MySQL uses SQL (Structured Query Language) to communicate with the server and perform database operations

Connecting Flutter with MySQL

There are several ways to connect Flutter with MySQL:

  • Using REST APIs
  • Using a plugin such as sqflite
  • Using a middleware such as PHP or Node.js

The choice of the method depends on the complexity of your application and your personal preference.

Using REST APIs

The most common way to connect Flutter with MySQL is by using REST APIs. REST (Representational State Transfer) is a software architectural style that uses HTTP requests to communicate between the client and server. With REST APIs, you can create a backend server that exposes endpoints for performing CRUD operations on the database. In Flutter, you can use the http package to make HTTP requests to the server.

Here is an example of how to fetch data from a MySQL database using REST APIs:


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

Future> fetchData() async {
  final response = await http.get(Uri.parse('http://localhost:3000/records'));

  if (response.statusCode == 200) {
    List data = jsonDecode(response.body);
    return data.map((record) => Record.fromJson(record)).toList();
  } else {
    throw Exception('Failed to fetch data');
  }
}

Using a Plugin such as sqflite

Another way to connect Flutter with MySQL is by using a plugin such as sqflite. Sqflite is a plugin that allows you to perform SQLite database operations in Flutter. Since SQLite is a lightweight database, you can use sqflite to store small amounts of data locally in the app. You can then use REST APIs or a middleware to communicate with the MySQL database on the server.

Here is an example of how to use sqflite to store data locally:


import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

Future initDatabase() async {
  return openDatabase(
    join(await getDatabasesPath(), 'my_database.db'),
    onCreate: (db, version) {
      return db.execute(
          'CREATE TABLE records(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)');
    },
    version: 1,
  );
}

Future insertRecord(Record record) async {
  final db = await initDatabase();

  await db.insert(
    'records',
    record.toMap(),
    conflictAlgorithm: ConflictAlgorithm.replace,
  );
}

Future> retrieveRecords() async {
  final db = await initDatabase();

  final List> maps = await db.query('records');

  return List.generate(maps.length, (i) {
    return Record(
      id: maps[i]['id'],
      name: maps[i]['name'],
      age: maps[i]['age'],
    );
  });
}

Using a Middleware such as PHP or Node.js

The third way to connect Flutter with MySQL is by using a middleware such as PHP or Node.js. A middleware acts as a bridge between the client and server and is responsible for handling the communication between them. With a middleware, you can write server-side code that interacts with the MySQL database and returns data to the client in a format that Flutter can understand.

Here is an example of how to use PHP as a middleware:


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

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
  // Handle GET request to retrieve data from the database
  $sql = "SELECT * FROM records";
  $result = $conn->query($sql);

  if ($result->num_rows > 0) {
    // Output data of each row
    $data = array();
    while($row = $result->fetch_assoc()) {
      $data[] = $row;
    }
    echo json_encode($data);
  } else {
    echo "0 results";
  }
} else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  // Handle POST request to insert data into the database
  $name = $_POST['name'];
  $age = $_POST['age'];

  $sql = "INSERT INTO records (name, age) VALUES ('$name', $age)";

  if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
  } else {
    echo "Error: " . $sql . "" . $conn->error;
  }
}

$conn->close();
?>

Conclusion

Flutter and MySQL are a powerful combination for building mobile apps with backend databases. By using REST APIs, plugins such as sqflite, or middlewares such as PHP or Node.js, you can easily connect Flutter with MySQL and perform CRUD operations on the database. Choose the method that suits your needs and start building amazing mobile apps!

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe