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.

Why SQLite in Flutter?
- Structured Data: Organize data in rows and columns using SQL.
- Offline Access: Data is stored locally, enabling offline functionality.
- Lightweight: Minimal resource consumption and no separate server required.
- Cross-Platform: Works seamlessly on Android and iOS with Flutter.
- Compatibility: Open-source and widely supported.
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:
- Creating a database.
- Defining tables and schemas.
- 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
- Proper Table Design: Use meaningful column names and appropriate data types.
- Avoid Overuse: Use SQLite only for structured data. For unstructured data, consider other solutions like Hive.
- Error Handling: Handle database exceptions to avoid crashes.
- Close Database Connections: Always close the database connection when it’s no longer needed.
- Data Migration: Plan schema migrations properly when upgrading the app version.
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…
- Introduction to Flutter and Dart
- Why choose Flutter
- Installing Flutter On Your Windows Mac And Linux System
- Your first Flutter app
- Flutter project structure
- Building blocks of Flutter
- Stateful vs. Stateless Widgets Explained
- Flutter layout system
- Flutter text widget
- Creating Buttons in Flutter: ElevatedButton, TextButton, and IconButton
- Handling User Input with Flutter Forms
- Container class in Flutter
- Flutter Navigation
- Flutter – Pass Data One Screen To Another Screen
- Managing Device Orientation in Flutter
- Stateful widget lifecycle in Flutter
- Future of Flutter
- Flutter Themes
- Flutter Animations
- Flutter AppBar Customization
- ListView in Flutter
- Flutter GridView
- Flutter Expanded Widget
- Flutter BottomNavigation Bar
- Floating Action Button
- Drawer Widgets in Flutter
- Form Validation in Flutter
- Flutter TextField
- Adding AdMob ads to a Flutter app
- Building Flutter Web & Desktop Applications
- What is Async and Await in Flutter
- HTTP requests in Flutter
- Parsing JSON in Flutter
- Tinder-Style Swipe Cards in Flutter
- Flutter Tic Tac Toe Game Tutorial
- Flutter Login UI Tutorial
- Flutter Card Widget Tutorial
- Flutter music player app tutorial
- Flutter introduction screens
- Shared Preferences in Flutter
- SQLite Database in Flutter
- Firebase Authentication in Flutter
- Firebase Firestore in Flutter
- Push Notifications in Flutter
- Handling File Uploads in Flutter
- Responsive Design in Flutter
- Provider in Flutter
- Riverpod in Flutter
- Flutter BLoC Pattern Tutorial