What is SQLite Database in Flutter

SQLite is an embedded, relational database that provides local data storage for mobile and desktop applications. With its lightweight architecture, SQLite is a perfect choice for mobile app developers to manage structured data efficiently.

SQLite Database in Flutter

Why SQLite in Flutter?

Setting Up SQLite in Flutter

To use SQLite in Flutter, we rely on the sqflite plugin. This plugin allows you to interact with SQLite databases easily.

1. Add Dependencies

In your pubspec.yaml file, include the following dependencies:

dependencies:  
sqflite: ^2.2.1
path: ^1.8.3

Run flutter pub get to install the packages.

2. Import the Packages

Import the necessary libraries in your Dart file:

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

SQLite Database Workflow in Flutter

The process of working with SQLite in Flutter involves:

  1. Creating a database.
  2. Defining tables and schemas.
  3. Performing CRUD (Create, Read, Update, Delete) operations.

Step 1: Create and Open a Database

To create a database, define a function that initializes it using the openDatabase method:

Future<Database> initializeDatabase() async {  
final databasePath = await getDatabasesPath();
final path = join(databasePath, 'app_database.db');

return openDatabase(
path,
version: 1,
onCreate: (db, version) {
db.execute('''
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
email TEXT
)
''');
},
);
}

Step 2: Insert Data

To add records to the database, use the insert method:

Future<void> insertUser(Database db, String name, String email) async {  
await db.insert(
'users',
{'name': name, 'email': email},
conflictAlgorithm: ConflictAlgorithm.replace,
);
}

Step 3: Retrieve Data

To fetch records, use the query method:

Future<List<Map<String, dynamic>>> getUsers(Database db) async {  
return await db.query('users');
}

Step 4: Update Data

To modify existing data, use the update method:

Future<void> updateUser(Database db, int id, String name, String email) async {  
await db.update(
'users',
{'name': name, 'email': email},
where: 'id = ?',
whereArgs: [id],
);
}

Step 5: Delete Data

To delete a record, use the delete method:

Future<void> deleteUser(Database db, int id) async {  
await db.delete(
'users',
where: 'id = ?',
whereArgs: [id],
);
}

Complete Example: User Management

Here’s a complete example of managing user data in a Flutter app:

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

void main() => runApp(MyApp());

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

class UserManagementScreen extends StatefulWidget {
@override
_UserManagementScreenState createState() => _UserManagementScreenState();
}

class _UserManagementScreenState extends State<UserManagementScreen> {
late Database database;

@override
void initState() {
super.initState();
initializeDatabase().then((db) {
setState(() {
database = db;
});
});
}

Future<Database> initializeDatabase() async {
final databasePath = await getDatabasesPath();
final path = join(databasePath, 'app_database.db');

return openDatabase(
path,
version: 1,
onCreate: (db, version) {
db.execute('''
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
email TEXT
)
''');
},
);
}

Future<void> addUser(String name, String email) async {
await database.insert('users', {'name': name, 'email': email});
setState(() {});
}

Future<List<Map<String, dynamic>>> fetchUsers() async {
return await database.query('users');
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('User Management')),
body: FutureBuilder(
future: fetchUsers(),
builder: (context, snapshot) {
if (!snapshot.hasData) return CircularProgressIndicator();
final users = snapshot.data as List<Map<String, dynamic>>;

return ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
final user = users[index];
return ListTile(
title: Text(user['name']),
subtitle: Text(user['email']),
);
},
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () => addUser('John Doe', 'john.doe@example.com'),
child: Icon(Icons.add),
),
);
}
}

Best Practices for SQLite in Flutter

Conclusion

SQLite is a powerful, reliable tool for managing local data storage in Flutter apps. By following this guide, you can integrate SQLite into your Flutter projects to handle structured data efficiently. Whether you’re building a to-do app or a complex system with offline capabilities, SQLite provides the tools you need for robust data management.

FAQs

Q1: Can I store large amounts of data in SQLite?
Yes, SQLite can handle large datasets, but for performance and scalability, consider alternatives like a cloud-based database for very large data needs.

Q2: How do I handle database migrations in Flutter?
You can use the onUpgrade callback in the openDatabase method to handle schema changes when the database version changes.

Q3: Is SQLite secure?
SQLite does not provide built-in encryption. For sensitive data, consider using plugins like sqflite_sqlcipher.

Explore Other Flutter Topics…

  1. Introduction to Flutter and Dart
  2. Why choose Flutter
  3. Installing Flutter On Your Windows Mac And Linux System
  4. Your first Flutter app
  5. Flutter project structure
  6. Building blocks of Flutter
  7. Stateful vs. Stateless Widgets Explained
  8. Flutter layout system
  9. Flutter text widget
  10. Creating Buttons in Flutter: ElevatedButton, TextButton, and IconButton
  11. Handling User Input with Flutter Forms
  12. Container class in Flutter
  13. Flutter Navigation
  14. Flutter – Pass Data One Screen To Another Screen
  15. Managing Device Orientation in Flutter
  16. Stateful widget lifecycle in Flutter
  17. Future of Flutter
  18. Flutter Themes
  19. Flutter Animations
  20. Flutter AppBar Customization
  21. ListView in Flutter
  22. Flutter GridView
  23. Flutter Expanded Widget
  24. Flutter BottomNavigation Bar
  25. Floating Action Button
  26. Drawer Widgets in Flutter
  27. Form Validation in Flutter
  28. Flutter TextField
  29. Adding AdMob ads to a Flutter app
  30. Building Flutter Web & Desktop Applications
  31. What is Async and Await in Flutter
  32. HTTP requests in Flutter
  33. Parsing JSON in Flutter
  34. Tinder-Style Swipe Cards in Flutter
  35. Flutter Tic Tac Toe Game Tutorial
  36. Flutter Login UI Tutorial
  37. Flutter Card Widget Tutorial
  38. Flutter music player app tutorial
  39. Flutter introduction screens
  40. Shared Preferences in Flutter
  41. SQLite Database in Flutter
  42. Firebase Authentication in Flutter
  43. Firebase Firestore in Flutter
  44. Push Notifications in Flutter
  45. Handling File Uploads in Flutter
  46. Responsive Design in Flutter
  47. Provider in Flutter
  48. Riverpod in Flutter
  49. Flutter BLoC Pattern Tutorial

Leave a Reply

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