SQLite local db in Flutter
To use the `sqflite` package for local database storage in your Flutter application, you can follow these steps:
1. Add `sqflite` to your `pubspec.yaml` file:
```yaml
dependencies:
sqflite: ^x.x.x # Use the latest version of sqflite
```
Replace `^x.x.x` with the latest version of the `sqflite` package available at the time you are adding it to your project.
2. Import the `sqflite` package and other necessary packages in your Dart code:
```dart
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart' as path;
```
3. Create a database helper class to manage your SQLite database. Here's a basic example of a database helper class:
```dart
class DatabaseHelper {
static final DatabaseHelper _instance = DatabaseHelper._internal();
factory DatabaseHelper() => _instance;
DatabaseHelper._internal();
late Database _database;
Future<void> initializeDatabase() async {
final databasePath = await getDatabasesPath();
final pathToDatabase = path.join(databasePath, 'my_database.db');
_database = await openDatabase(
pathToDatabase,
version: 1,
onCreate: (db, version) async {
// Create tables and define schema here
await db.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
email TEXT
)
''');
},
);
}
Future<void> insertUser(Map<String, dynamic> userData) async {
await _database.insert('users', userData);
}
Future<List<Map<String, dynamic>>> getUsers() async {
return await _database.query('users');
}
Future<void> updateUser(int id, Map<String, dynamic> userData) async {
await _database.update('users', userData, where: 'id = ?', whereArgs: [id]);
}
Future<void> deleteUser(int id) async {
await _database.delete('users', where: 'id = ?', whereArgs: [id]);
}
}
```
In this example, the `DatabaseHelper` class creates and manages a SQLite database with a table named 'users'. You can customize this class to match your data model and database schema.
4. Initialize and open the database in your app, typically in the `main` function or `main.dart` file:
```dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final databaseHelper = DatabaseHelper();
await databaseHelper.initializeDatabase();
runApp(MyApp());
}
```
5. Use the `DatabaseHelper` methods to interact with the database in your app. For example, you can insert, retrieve, update, and delete data as needed.
```dart
final databaseHelper = DatabaseHelper();
// Insert a user
await databaseHelper.insertUser({'name': 'John Doe', 'email': 'john@example.com'});
// Retrieve users
final users = await databaseHelper.getUsers();
// Update a user
await databaseHelper.updateUser(1, {'name': 'Updated Name', 'email': 'updated@example.com'});
// Delete a user
await databaseHelper.deleteUser(1);
```
6. Ensure that you close the database when your app is done using it:
```dart
await databaseHelper.close();
```
These are the basic steps for using the `sqflite` package to create and manage a local SQLite database in your Flutter app. You can customize the database schema and operations to suit your application's specific needs.
Comments
Post a Comment