Flutter is a mobile app framework that allows you to build native apps for Android and iOS with a single codebase. Flutter provides various plugins to make it easy for you to work with databases, one of which is the `sqflite` plugin.
Creating a Database
Here is an example of how to create a database with the `sqflite` plugin:
import 'package:sqflite/sqflite.dart'; Future<void> main() async { // Get the path to the database final String databasePath = await getDatabasesPath(); final String path = join(databasePath, 'my_database.db'); // Open the database Database database = await openDatabase( path, version: 1, onCreate: (Database db, int version) async { // Execute a query to create a table await db.execute(''' CREATE TABLE users ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER NOT NULL ) '''); }, ); } |
The code above will create a new database named `my_database.db` in the app's default database location. This database has one table named `users` with three columns: `id`, `name`, and `age`.
Adding Data
Here is an example of how to add data to the `users` table:
Future<void> addUser(String name, int age) async { |
The code above will insert new data into the `users` table with the given name and age.
Retrieving Data
Here is an example of how to retrieve data from the `users` table:
Future<List<Map<String, dynamic>>> getAllUsers() async { |
The code above will retrieve all data from the `users` table and return it as a list of maps.
Editing Data
Here is an example of how to edit data in the `users` table:
Future<void> updateUser(int id, String name, int age) async { |
The code above will update the data in the `users` table with the given name and age for the user with the given ID.
Deleting Data
Here is an example of how to delete data from the `users` table:
Future<void> deleteUser(int id) async { |
The code above will delete data from the `users` table with the given ID.
Flutter provides various plugins to make it easy for you to work with databases. The `sqflite` plugin is one of the popular and easy-to-use plugins. You can use this plugin to create, delete, and edit databases easily.
Note :
* Make sure you have installed the `sqflite` plugin in your project.
* You can find the complete documentation for the `sqflite` plugin at [https://pub.dev/documentation/sqflite/latest/sqflite/sqflite-library.html](https://pub.dev/documentation/sqflite/latest/sqflite/sqflite-library.html).
Complete Example
Here is a complete example of how to create, delete, and edit a database with Flutter:
import 'package:flutter/material.dart'; |