Skip to main content

Learn SQLite using flutter

What Is SQLite

SQLite is an open source relational database, it is used to create a database, perform different operation like add, delete and remove data.

SQLite setup

Add the required dependencies. For this article, you’ll need the sqflite package for using the SQLite database.













Open a simulator device or connect a real device to your system and start the app using the following command:

flutter run

Add your SQLite file which you want to read and write.









Place your file under assets folder like below image

























Create DBQueries and DBProvider.

DBProvider is require to connect your app with database.



import 'dart:io';

import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class DBProvider {
static final DBProvider _instance = new DBProvider.internal();

factory DBProvider() => _instance;
static Database _database;

Future<Database> get database async {
if (_database != null) return _database;

// if _database is null we instantiate it
_database = await initDB();
return _database;
}

DBProvider.internal();

initDB() async {
var documentsDirectory = await getDatabasesPath();
String path = join(documentsDirectory, "app.db");
// var taskDb = await openDatabase(path, version: 1);
await deleteDatabase(path);
// Create the writable database file from the bundled demo database file:
ByteData data = await rootBundle.load("assets/db/mydb.sqlite");
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
await File(path).writeAsBytes(bytes);
_database = await openDatabase(path);
return _database;
}

}

Inside DB queries you have write all the SQL queries that wants in your app.All the sql queries must be asynchronised.


class DBQueries {
var _database;
DBProvider dbProvider;

DBQueries() {
getDb();
}

getDb() async {
/// Initialize sq-lite
dbProvider = await DBProvider();
}

initializeDB() async {
_database = await dbProvider.initDB();
}

Future<int> createCategory(Category category) async {
var result = await _database.insert("Category", category.toJson());
return result;
}

Future<List> getCategory() async {
var result = await _database.rawQuery('SELECT * FROM Category');
return result.toList();
}

Future<Category> getCategoryById(int id) async {
var results =
await _database.rawQuery('SELECT * FROM Category WHERE id = $id');

if (results.length > 0) {
return new Category.fromJson(results.first);
}

return null;
}

Future<int> updateCategory(Category category) async {
return await _database.rawUpdate(
'UPDATE Category SET name = ${category.name} WHERE id = ${category.id}');
}

Future<int> deleteCategory(int id) async {
return await _database.rawDelete('DELETE FROM Category WHERE id = $id');
}


closedatabase() async {
await _database.close();
}
}

Let's access DBQueries from your main.dart

@override

void initState() {
// TODO: implement initState
_accessDatabase();
super.initState();
}
 Future<void> _accessDatabase() async {
  var db = await DBQueries();
await db.initializeDB();
var category = await db.getCategory();
for (int i = 0; i < category.length; i++) {
categories.add(Category.fromJson(category[0]));
}
print( Category.fromJson(category[0]).name);
}


Comments

Post a Comment

Popular posts from this blog

Designing and Building Dual-Screen Apps for Concept "iPhone Duo" in Flutter

FLUTTER • ADAPTIVE UI • CONCEPT DESIGN Designing and Building Dual-Screen Apps for the Concept “iPhone Duo” in Flutter Explore adaptive layouts, two-pane navigation, simulated dual-screen experiences, and the engineering decisions behind apps designed for two displays. Reading time: 10–12 minutes Concept disclaimer: “iPhone Duo” is used here as a hypothetical dual-screen device concept, not as a claim that Apple has announced or released such a product. Flutter examples in this article demonstrate adaptive and simulated two-pane layouts that can be tested on existing devices. What if an iPhone could provide two displays that work together? Imagine reading an article on one screen while keeping notes on the other, browsing a product list beside its details, or viewing a video while controlling playback on a separate panel. This kind of experience introduces an interesting app-design challenge: the interface must understand how much space is avail...

Dynamic and responsive ListView in flutter

How to create responsive and dynamic Listview? Step 1: Create Listview builder ListView.builder( physics: ScrollPhysics(parent: AlwaysScrollableScrollPhysics()), itemCount: allBillList[ 0 ].data!.length, scrollDirection: Axis.vertical, itemBuilder: (c, index1) { String data = mainList![index1]; return ListItem(data); }) Step 2: Create separate ListItem.dart file import 'package:flutter/cupertino.dart' ; import 'package:flutter/material.dart' ; class ListItem extends StatefulWidget { ListItem({ this .data}); final String? data; @override _ListItemState createState() => _ListItemState(); } class _ListItemState extends State<ListItem> { @override Widget build(BuildContext context) { // TODO: implement build return Column( children: [ Container(margin: const EdgeInsets.all( 16.0 ), child:Text(data)), BasicWidget.getDivider(), ], ); } } So if you want to delete or add items in main...

Building Dual-Screen & Foldable ListView Apps in Flutter using TwoPane

Flutter Tutorial Building Dual-Screen & Foldable ListView Apps in Flutter using TwoPane Learn how to adapt your Flutter layout for dual-screen and foldable devices using Microsoft's dual_screen package and Flutter's TwoPane widget. Dual-screen and foldable mobile devices offer unique screen real estate. Instead of showing a single list view that navigates to a new page, dual-screen layouts allow developers to display a Master-Detail view side-by-side when unfolded or on dual screens, and fall back to a single page view on standard phones. What You Will Learn: Understanding Dual-Screen Hinge and Folding Display Features Implementing the TwoPane widget for responsive multi-screen layouts Handling Master-Detail state selection dynamically Material 3 visual layout standards for adaptive design 1. Step 1: Add Dependencies Add the official dual_screen ...

Flutter Bloc Pattern 9.1.1 Call API

Flutter Architecture Tutorial How to Fetch API Data & Display in ListView Using Flutter BLoC Pattern Build a clean Flutter app that fetches users from a REST API, manages loading and error states with BLoC, and displays results in a ListView. Fetching data from a REST API and displaying it in a scrolling list is one of the most common tasks in Flutter development. As an app grows, keeping network requests, UI code, and state management mixed together can make the code difficult to test and maintain. The BLoC (Business Logic Component) pattern helps separate business logic from the presentation layer. In this tutorial, we’ll build a small example using flutter_bloc , http , and a public sample API. You’ll learn how to handle loading, success, empty, and error states without placing API logic directly inside the widget. What we’ll build Fetch a list of users from a REST endpoint Create a model, repository, BLoC, events, and st...

A Complete Guide to Publishing a Flutter App on the Apple App Store

Flutter • iOS • App Store Connect A Complete Guide to Publishing a Flutter App on the Apple App Store From your first iOS release build to TestFlight, App Review, and a successful App Store launch. Who is this guide for? Flutter developers who have an app ready for iOS distribution. You need a Mac with a compatible version of Xcode and access to the Apple Developer Program. Apple requirements change, so verify current policies before submitting. Publishing workflow at a glance 👤 1. Account Developer Program ⚙️ 2. Configure Bundle ID and signing 📦 3. Build Archive and upload 🚀 4. Release Review and launch 1. Prerequisites Mac and Xcode: iOS builds and signing require macOS and Xcode. Use versions supported by your Flutter SDK and accepted by App Store Connect. Flutter SDK: Use a stable release and check that your plugins support the target iOS version. Apple Developer Program: Enroll if you need App Store distribution. Membership terms and fees depend on your r...

How to Write Test Cases in Flutter: A Complete Guide with Examples

Flutter Testing Handbook How to Write Test Cases in Flutter: A Complete Guide with Examples Learn how to write unit, widget, and integration tests in Flutter—with practical Dart examples, testable app structure, and commands you can use in your project. Testing helps you catch bugs early, protect existing features when code changes, and ship Flutter apps with greater confidence. Instead of manually checking every screen after each update, you can automate many checks and run them whenever you change your code. In this guide, we’ll cover the main Flutter testing types, set up a test environment, write examples for business logic and UI, test asynchronous behavior, mock dependencies, and run tests from the command line. What you’ll learn How unit, widget, and integration tests differ How to create and run a Flutter test file How to test validation, calculations, buttons, and displayed text How to handle asynchronous ...
  Implementing Search by Character in Flutter: A Complete Guide with Examples Searching is one of the most common features in mobile applications. Whether you're building a contact list, product catalog, employee directory, or chat application, users expect search results to update instantly as they type. Flutter makes it easy to implement search by character , where the list filters after every keystroke without requiring users to tap a search button. In this guide, you'll learn how to implement a fast, efficient, and scalable character-by-character search in Flutter. What is Search by Character? Search by character (also called live search or incremental search ) filters data every time the user types a new character. For example: User Types Results ---------------------------------------- A Apple, Amazon, Adobe Ap Apple App Apple Appl Apple Apple Apple Instead of waiting for the user to...

Manage Firebase storage using flutter

Flutter • Firebase • Mobile Development Manage Firebase Storage Using Flutter A practical, end-to-end guide to uploading, monitoring, listing, downloading, and deleting files securely with Cloud Storage for Firebase. Beginner friendly Working code examples Security rules What you will build: a small Flutter file manager that uploads a selected file, shows upload progress, retrieves its download URL, lists files in a user folder, and deletes a selected file. The examples assume Firebase Authentication is enabled and the user is signed in. 1. What is Firebase Storage? Cloud Storage for Firebase stores user-generated content such as profile pictures, receipts, PDFs, videos, and documents. Flutter communicates with the Firebase Storage SDK; the SDK sends the file to a storage bucket, where Firebase Security Rules decide whether the request is allowed. 📱 Flutter app Selects the file → 🔐 Firebase SDK Checks request access ...

Customised Flutter AppBar

Create centralized AppBar for all screens at one place. In just 2 steps you create your own appBar. 1) Create AppBar.dart here you have to pass true and false to showRight and inside rightWidget pass widget from parent screen.(check step 2) class  AppBarWidget { static getAppBar (String title, [showRight, rightWidget]) { if (showRight == null ) { showRight = false ; } return AppBar ( // Here we take the value from the MyHomePage object that was created by // the App.build method, and use it to set our appbar title. backgroundColor: Colors. white , title: Text ( title, style: TextStyle (color: AppColors. btn_primary_dark_new ,fontWeight: FontWeight. w600 ), ), centerTitle: true , leadingWidth: 100 , leading: Padding ( padding: const EdgeInsetsDirectional . only (start: 8.0 ), child: InkWell ( onTap: () { Get.back(); }, child: Row ( ...