Connecting a Flutter Desktop App to MySQL Database
Flutter is an open source UI framework by Google, allowing developers to build native mobile, web and desktop applications from a single codebase using its own language, Dart. But managing app data often requires database integration. This post will guide you through connecting Flutter to MySQL.
Setting up a MySQL Database :
1. Install MySQL Server: Download and install MySQL server from the official website.
2. Create a Database and Tables : Open a MySQL client like MySQL Workbench and create a new database to store your Flutter app data.
design your database by creating tables with required fields and relationships to efficiently structure your data.
Connecting Flutter to MySQL:
1. Add Dependencies: Include the mysql1
package in your pubspec.yaml
file and run flutter pub get
to incorporate it into your project.
dependencies:
mysql1: ^0.20.0
Establish the Connection:
Import the necessary package in your dart code:
import 'package:mysql1/mysql1.dart';
Use MySqlConnection
class to connect:
//Make sure that database is created before connect.
var settings = ConnectionSettings(
host: 'localhost', // Add your host IP address or server name
port: 3307, // Add the port the server is running on
user: 'root', // Your username
password: 'root', // Your password
db: 'test', // Your Database name
);
conn = await MySqlConnection.connect(settings);
// print('Connected to the database');
setState(() {
_isConnected = true; // Set connection status to true
});
Once connected you can perform Database CRUD operations:
Creating Data:
var result = await conn.query('INSERT INTO users (username, password, email) VALUES (?, ?, ?)', ['Saikat Mondal', 'Password', 'saikat.mondal@defineway.com']);
var userId = result.insertId;
print(userId);
Reading Data:
var result = await conn.query('SELECT * FROM users');
for (var row in result) {
print('Id: ${row['id']}, Username: ${row['username']}, Password: ${row['password']}, Email: ${row['email']}');
}
Update Data:
var result = await conn.query('UPDATE users SET username = ?, password = ? WHERE id = ?', ['Saikat', 'Password', 27]);
Deleting Data:
var result = await conn.query('DELETE FROM users WHERE id= ?', [27]);
2 Comments
Christoper
November 23, 2024Awesome blog! Ɗo үou have any recommendations for asрiring wгiteгs?
I’m planning to start my own site soon but I’m a little ⅼost on everything.
Wouⅼd you advise starting with a free platfоrm like WordPress or go for a paid option? There are so many choices out there that I’m totally overѡhelmed ..
Any ideas? Thɑnk you!
Saikat Mondal
November 23, 2024Thank you for your kind words! It’s fantastic that you are planning to start your own site. If you’re just getting started and want to test things out without financial commitment, a free platform like WordPress is a good place to begin.