SQLite is a very popular choice of local storage database. It is an SQL lightweight and serverless database engine that is highly efficient and user-friendly. Flutter, Google's UI toolkit for building natively compiled applications, doesn't come with built-in support for local data storage but provides robust support for integrating SQLite databases. Therefore SQLite can be easily integrated into Flutter projects to store and retrieve structured data locally.
In this article, we will get to know how can we integrate and use the SQLite database with the Flutter project, Stepwise with an example of the user management database of Geeksforgeeks.
Prerequisites
Before we dive in, there are a few things you'll need to have:
- Basic knowledge of Flutter and Dart
- Flutter SDK installed
- Dart SDK installed
- IDEs such as VSCode & Android Studio
Having these prerequisites in place will set you up for success as we move forward. So, make sure you have them ready before we get started.
Steps to Integrate SQLite Database in Flutter
Step 1: Set Up the Flutter Project
Create a new Flutter project named 'sql_example' using the following command:
flutter create sql_example
cd sql_example
Example :
Step 2 : Adding Dependencies
To get started, open up your pubsec.yaml file in the project structure. Now, you'll want to add the following dependencies:
dependencies:
flutter:
sdk: flutter
sqflite: ^2.2.6
path: ^1.8.3
path_provider: ^2.0.14
- sqflite is the package that provides SQLite integration for Flutter.
- path is a package that helps in locating the database file path.
Run flutter pub get to install the dependencies.
Step 3 : Defining the User Model
Create a file in the 'lib/user.dart' to define a model class to represent user data. Here's an example of a simple gfg user model class, that has user id , username and an email, along with a constructor that initialize the data members :
user.dart
class User {
final int? id;
final String username;
final String email;
User({this.id, required this.username, required this.email});
Map<String, dynamic> toMap() {
return {'id': id, 'username': username, 'email': email};
}
factory User.fromMap(Map<String, dynamic> map) {
return User(
id: map['id'],
username: map['username'],
email: map['email'],
);
}
}
Step 4 : Defining the Database Class
In Database helper class we have all the functions are implemented here, Database class has the following methods
- initDb(): function is used to initialize the database. It checks if the 'gfg_users' table exists, and if it doesn't, it creates it.
- _onCreate(): It is a callback function that gets executed when the database is created. Its purpose is to define the schema of the 'users' table.
- insertUser(): To insert a new user into the 'gfg_users' table .
- queryAllUsers(): Retrieves all users from the 'gfg_users' table.
- updateUser(): To Update an existing user in the 'gfg_users' table.
- deleteUser(): Deletes a user from the 'gfg_users' table by their ID.
database_helper.dart
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'user.dart';
class DatabaseHelper {
static final DatabaseHelper instance = DatabaseHelper._instance();
static Database? _database;
DatabaseHelper._instance();
Future<Database> get db async {
_database ??= await initDb();
return _database!;
}
Future<Database> initDb() async {
String databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'geeksforgeeks.db');
return await openDatabase(path, version: 1, onCreate: _onCreate);
}
Future _onCreate(Database db, int version) async {
await db.execute('''
CREATE TABLE gfg_users (
id INTEGER PRIMARY KEY,
username TEXT,
email TEXT
)
''');
}
Future<int> insertUser(User user) async {
Database db = await instance.db;
return await db.insert('gfg_users', user.toMap());
}
Future<List<Map<String, dynamic>>> queryAllUsers() async {
Database db = await instance.db;
return await db.query('gfg_users');
}
Future<int> updateUser(User user) async {
Database db = await instance.db;
return await db.update('gfg_users', user.toMap(), where: 'id = ?', whereArgs: [user.id]);
}
Future<int> deleteUser(int id) async {
Database db = await instance.db;
return await db.delete('gfg_users', where: 'id = ?', whereArgs: [id]);
}
Future<void> initializeUsers() async {
List<User> usersToAdd = [
User(username: 'John', email: '[email protected]'),
User(username: 'Jane', email: '[email protected]'),
User(username: 'Alice', email: '[email protected]'),
User(username: 'Bob', email: '[email protected]'),
];
for (User user in usersToAdd) {
await insertUser(user);
}
}
}
Step 5 : Defining the main file
- Initialization: We make sure to initialize the database and insert the users ,before running the MyApp widget.
- User List Display: The UserList widget is responsible for displaying the list of users that we fetch from the database using the DatabaseHelper class.
- State Management: To keep things organized, we use the initState method to fetch the users when the widget is first initialized and update the user interface accordingly.
- User Display: We show each user's username and email using a ListTile widget within a ListView.builder.
main.dart
import 'package:flutter/material.dart';
import 'database_helper.dart'; // Import the DatabaseHelper class
import 'user.dart'; // Import the User class
void main() async {
// Initialize the database and insert users
WidgetsFlutterBinding.ensureInitialized();
await DatabaseHelper.instance.initDb();
await DatabaseHelper.instance.initializeUsers();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'User Management',
home: UserList(),
);
}
}
class UserList extends StatefulWidget {
@override
_UserListState createState() => _UserListState();
}
class _UserListState extends State<UserList> {
List<User> _users = [];
@override
void initState() {
super.initState();
_fetchUsers();
}
Future<void> _fetchUsers() async {
final userMaps = await DatabaseHelper.instance.queryAllUsers();
setState(() {
_users = userMaps.map((userMap) => User.fromMap(userMap)).toList();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('GFG User List'),
backgroundColor: Colors.lightGreen,
),
body: ListView.builder(
itemCount: _users.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_users[index].username),
subtitle: Text(_users[index].email),
);
},
),
);
}
}
Output:
output.pngThus , by following this steps we can integrate SQLite in Flutter project .
Similar Reads
Flutter - initState()
There are two types of widgets provided in Flutter. The Stateless WidgetThe Stateful Widget As the name suggests Stateful Widgets are made up of some 'States'. The initState() is a method that is called when an object for your stateful widget is created and inserted inside the widget tree. It is bas
4 min read
Table Widget in Flutter
Table widget is used to display items in a table layout. There is no need to use Rows and Columns to create a table. If we have multiple rows with the same width of columns then Table widget is the right approach. SliverList or Column will be most suitable if we only want to have a single column. Th
3 min read
Web Scraping in Flutter
The process of extracting required data/information from a web page by accessing the HTML of the web page is called Web Scraping or Web Harvesting or Web Data Extraction. This article discusses the steps involved in Web Scraping by using Flutter's html and http packages. Step 1: Set up a new Flutter
6 min read
Listview.builder in Flutter
ListView is a very important widget in a flutter. It is used to create the list of children But when we want to create a list recursively without writing code again and again then ListView.builder is used instead of ListView. Â ListView.builder creates a scrollable, linear array of widgets. ListView.
3 min read
Review System in Flutter
In this article, we will implement a review system in the flutter application like you see many times when you purchase a product online from Amazon, Flipkart, or any other company then these companies asked you to give your review regarding the product. Now, this article helps you to guide how you
4 min read
Flutter - GridView
Flutter's GridView is a widget similar to a 2-D array found in many programming languages. As its name indicates, the GridView widget is used to display content in a grid format. This allows us to showcase images, text, icons, and more within the GridView. There are several ways to implement GridVie
6 min read
Input Quantity in Flutter
A Flutter widget for quantity input. Increase or decrease the input value by pressing the button. Built with a text field, InputQty also supports typing input quantity manually. The input value will automatically return to the preset maximum/minimum value. The cursor will automatically move to the r
3 min read
Persist Data with SQLite in Flutter
SQLite is an open-source computer database, it's wont to store a piece of information, perform completely different operations like add, delete, and update. SQLite doesn't need a server or backend code; all the info is saved to a computer file within the device, or we can say it's native to storage.
7 min read
What is Widgets in Flutter?
Flutter is Google's UI toolkit for crafting beautiful, natively compiled iOS and Android apps from a single code base. To build any application we start with widgets - The building block of Flutter applications. Widgets describe what their view should look like given their current configuration and
5 min read
Flutter with HTML
Flutter is growing with its libraries and community. Earlier, we could use Machine Learning and Flutter together to create powerful applications. Now, we can combine Flutter and HTML too. If there is a static HTML webpage that we want to render in our application that is built using Flutter. With th
6 min read