Complete SQLite CRUD operations in Flutter

Complete SQLite CRUD operations in Flutter

Are you a Flutter developer looking for a reliable way to handle local data storage? Look no further! SQLite is here to simplify your life.

What is SQLite?

  • SQLite is a C-language library that serves as a self-contained, high-reliability SQL database engine.
  • Most Used: SQLite stands as one of the most widely used database engines worldwide, admired for its efficiency and versatility.
  • Prevalence: It’s not just for developers; SQLite is built into countless mobile phones, computers, and everyday applications that we use, making it an integral part of our digital lives.

Why Choose SQLite?

  • Performance: Sqflite offers high-performance local data storage, making it suitable for apps of all sizes.
  • Simplicity: With a straightforward API, you can quickly create, read, update, and delete records.
  • Cross-Platform: Flutter is all about cross-platform development, and Sqflite follows suit, supporting both Android and iOS.

Well-Known Users of SQLite

SQLite boasts a widespread user base, including tech giants like Google and Apple. Its simplicity and efficiency make it a trusted choice for various applications. Explore the list of famous users on SQLite’s website.

What is Sqflite?

Sqflite is a Flutter package that provides a simple and efficient way to work with SQLite databases in your Flutter applications. It’s lightweight, easy to use, and perfect for managing your local data. Everything in this package is asynchronous.


Get Started with Sqflite Today!

Start harnessing the potential of Sqflite today, whether you’re crafting a minimalist to-do list or embarking on a feature-rich mobile app journey. Sqflite is your key to efficient and robust local data storage in Flutter!

Fully functional app built with SQLite integration.

To integrate SQLite functionality in your Flutter project, follow these steps:

1. Add dependency by open thepubspec.yaml file in your project directory.

dependencies:   
flutter:
sdk: flutter

# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2

# Dependencies of SQLITE
sqflite: ^2.2.0+3 # SQLite Plugin Link https://pub.dev/packages/sqflite
path: ^1.8.0 # Path Plugin Link https://pub.dev/packages/path
path_provider: ^2.1.1 # Path Provider Plugin Link https://pub.dev/packages/path_provider
  • sqflite: This package provides SQLite database functionality for your Flutter app.
  • path_provider: This package allows you to specify the path to the database on your device.

3. Or use command to add the packages as a dependency, run flutter pub add

flutter pub add sqflite path path-provider

2. After adding these dependencies, run flutter pub get and flutter pub upgrade to fetch and install the packages.

Let’s structure a simple Flutter application with Sqflite using an Object-Oriented Programming (OOP) approach. We’ll create a class to encapsulate database operations and model classes for our data.

Create Model Class

  • Create a new file inside the ‘lib’ folder.
  • In that file, create a model class with the required properties.
  • Implement a `toJson` method within the model class to map its properties into JSON format.
  • Implement a `fromJson` method to convert JSON data fetched from the database into an instance of the Model class.
  • Both the `toJson` and `fromJson` methods are user-defined and customized to handle the specific data conversion requirements.
class NoteModel {
// Define class properties
int? id; // User ID
String? title; // User name
String? description; // User email

// Constructor with optional 'id' parameter
NoteModel(this.title, this.description, {this.id});

// Convert a Note into a Map. The keys must correspond to the names of the
// columns in the database.
NoteModel.fromJson(Map<String, dynamic> map) {
id = map['id'];
title = map['title'];
description = map['description'];
}

// Method to convert a 'NoteModel' to a map
Map<String, dynamic> toJson() {
return {
'title': title,
'description': description,
};
}
}

Create Database Method

  • Adding the imports: add the required imports to the database helper file.
// Import the plugins Path provider and SQLite.
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart';
  • Open the database: To open the database we use openDatabase the method takes the path and returns a Database object.
  • Initialize the database: declare a function which uses the above imports to open a database connection.
_initDatabase() async {
io.Directory documentsDirectory = await getApplicationDocumentsDirectory();

// Set the path to the database. Note: Using the `join` function from the
// `path` package is best practice to ensure the path is correctly
// constructed for each platform.
String path = join(documentsDirectory.path, databaseName);
// When the database is first created, create a table to store Notes.
var db =
await openDatabase(path, version: versionNumber, onCreate: _onCreate);
return db;
}

// Run the CREATE TABLE statement on the database.
_onCreate(Database db, int intVersion) async {
await db.execute("CREATE TABLE IF NOT EXISTS $tableNotes ("
" $colId INTEGER PRIMARY KEY AUTOINCREMENT, "
" $colTitle TEXT NOT NULL, "
" $colDescription TEXT"
")");
}

CRUD Operations

Perform CRUD (Create, Read, Update, Delete) operations on your database.

1. Create

  • To perform operations on a database, the database must be opened.
  • After the database is open, the returned database object can be utilized for a range of operations.
  • When it comes to data insertion, the insert method is employed.
  • Data insertion typically involves structuring the data in JSON format.
// Define a function that inserts notes into the database
Future<void> insert(NoteModel note) async {
// Get a reference to the database.
final db = await database;

// Insert the Note into the correct table. You might also specify the
// `conflictAlgorithm` to use in case the same Note is inserted twice.
//
// In this case, replace any previous data.
await db.insert(tableNotes, note.toJson(),
conflictAlgorithm: ConflictAlgorithm.replace);
}

2. Read

  • With sqflite, data querying offers various options using arguments like where, groupBy, having, orderBy, and columns within the query() helper.
// A method that retrieves all the notes from the Notes table.
Future<List<NoteModel>> getAll() async {
// Get a reference to the database.
final db = await database;

// Query the table for all The Notes. {SELECT * FROM Notes ORDER BY Id ASC}
final result = await db.query(tableNotes, orderBy: '$colId ASC');

// Convert the List<Map<String, dynamic> into a List<Note>.
return result.map((json) => NoteModel.fromJson(json)).toList();
}

3. Update

  • Use update() helper to update any record in the database. To update specific records, use the where argument.
// Define a function to update a note
Future<int> update(NoteModel note) async {
// Get a reference to the database.
final db = await database;

// Update the given Note.
var res = await db.update(tableNotes, note.toJson(),
// Ensure that the Note has a matching id.
where: '$colId = ?',
// Pass the Note's id as a whereArg to prevent SQL injection.
whereArgs: [note.id]);
return res;
}

4. Delete

  • Use the where argument in delete() helper to delete specific rows from the table.
  • Remember to use whereArgs to pass arguments to where statement in order to prevent SQL injection attacks.
// Define a function to delete a note
Future<void> delete(int id) async {
// Get a reference to the database.
final db = await database;
try {
// Remove the Note from the database.
await db.delete(tableNotes,
// Use a `where` clause to delete a specific Note.
where: "$colId = ?",
// Pass the Dog's id as a whereArg to prevent SQL injection.
whereArgs: [id]);
} catch (err) {
debugPrint("Something went wrong when deleting an item: $err");
}
}

Always use whereArgs in Sqflite to prevent SQL injection attacks. This safeguards your Flutter application by ensuring proper sanitation of user inputs and data passed to the where statement.

Leveraging Gemini AI for Efficient Flutter Development in Android Studio

 Leveraging Gemini AI for Efficient Flutter Development in Android Studio

As the world of AI continues to evolve, integrating advanced AI tools into mobile applications becomes increasingly feasible. Gemini AI, a powerful AI solution, can be leveraged within Flutter applications to add sophisticated functionalities. This article will guide you through using Gemini AI with Flutter in Android Studio, showcasing various examples to get you started.

Prerequisites

Before diving into the integration, ensure you have:

  1. Android Studio installed and updated.
  2. Flutter SDK set up and configured.
  3. Gemini AI API credentials (API key, endpoint).

Setting Up Flutter Project

Create a New Flutter Project:

  • Open Android Studio.
  • Select New Flutter Project.
  • Follow the wizard to set up your project.

Using Gemini AI for Code Assistance in Android Studio with Flutter

1. Setup Gemini AI in Android Studio

To integrate Gemini AI or a similar code assistant tool into Android Studio, follow these steps:

Install Gemini AI Plugin:

  • Open Android Studio.
  • Go to File > Settings (or Android Studio > Preferences on macOS).
  • Select Plugins from the sidebar.
  • Search for the Gemini AI plugin or the relevant code assistant plugin in the marketplace.
  • Click Install and restart Android Studio if prompted.

Configure API Key and Settings:

  • Open Settings again.
  • Navigate to Tools > Gemini AI (or the relevant section for the code assistant plugin).
  • Enter your API key and configure other settings as required.

2. Using Gemini AI for Flutter Code Assistance

Once the plugin is installed and configured, you can leverage Gemini AI to assist with writing Flutter code in several ways:

Code Autocompletion:

  • As you type Flutter code, Gemini AI can suggest completions based on your context. This is especially useful for writing repetitive code or exploring Flutter widgets and methods.
  • Example: Start typing Container and Gemini AI might suggest various properties like paddingmargin, and alignment.

Code Snippets and Templates:

  • Gemini AI can generate code snippets or complete code templates for common Flutter tasks.
  • Example: Type a comment like // Create a Flutter ListView and Gemini AI might provide a complete ListView implementation.

Refactoring and Code Improvement:

  • Gemini AI can analyze your code and suggest improvements or refactorings. This can help you adhere to best practices and optimize your Flutter code.
  • Example: If you have a long build method, Gemini AI might suggest breaking it into smaller widgets.

Documentation and Examples:

  • Use Gemini AI to get explanations or examples of Flutter widgets and libraries. This can be helpful when you’re learning new APIs or need to understand usage quickly.
  • Example: Type TextEditingController and Gemini AI might provide a brief explanation and usage example.

Error Detection and Fixes:

  • As you code, Gemini AI can help identify potential errors or issues and suggest fixes.
  • Example: If you miss a required parameter in a widget, Gemini AI might highlight the issue and suggest the correct parameter.

3. Examples of Using Gemini AI in Practice

Here are some practical examples of how you might use Gemini AI in your Flutter development:

Creating a Flutter Layout:

  • Without Gemini AI: You might manually look up the properties for a Column and Row.
  • With Gemini AI: Start typing Column and Gemini AI suggests a complete layout structure with common properties and child widgets.
Column(
children: [
Text('Title'),
ElevatedButton(
onPressed: () {},
child: Text('Click Me'),
),
],
)

Implementing State Management:

  • Without Gemini AI: You write the code for Provider or Bloc from scratch.
  • With Gemini AI: Type Provider setup and Gemini AI generates the code for setting up Provider with example usage.
class CounterProvider extends ChangeNotifier {
int _count = 0;

int get count => _count;

void increment() {
_count++;
notifyListeners();
}
}

void main() {
runApp(
ChangeNotifierProvider(
create: (context) => CounterProvider(),
child: MyApp(),
),
);
}

Fetching Data from an API:

  • Without Gemini AI: Write all the code for making HTTP requests, handling responses, and parsing JSON.
  • With Gemini AI: Type Fetch data from API and Gemini AI provides a complete function for fetching data from an endpoint.
Future<void> fetchData() async {
final response = await http.get(Uri.parse('https://api.example.com/data'));

if (response.statusCode == 200) {
var data = jsonDecode(response.body);
// Process data
} else {
throw Exception('Failed to load data');
}
}

4. Tips for Maximizing Gemini AI Assistance

Use Contextual Comments:

  • Write comments or descriptive text about what you want to achieve, and Gemini AI can generate the corresponding code.

Iterate and Customize:

  • Review and modify the code suggestions provided by Gemini AI to fit your specific needs and coding style.

Learn from Suggestions:

  • Analyze the suggestions and snippets provided to learn new Flutter techniques and best practices.

Conclusion

Integrating Gemini AI with Android Studio for Flutter development can significantly boost your productivity and streamline your coding process. By following the setup steps and leveraging Gemini AI’s code assistance features, you can efficiently write, refactor, and improve your Flutter applications. Embrace the AI-driven development experience to enhance your coding workflow and stay ahead in the rapidly evolving world of Flutter development.

How to extract filename from Uri?

Now, we can extract filename with and without extension :) You will convert your bitmap to uri and get the real path of your file. Now w...