Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Flutter Database in Android

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how to use Flutter database in Android, has certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand it.

Description

Flutter natively does not support database operations, it uses SQLlit plug-ins to make applications have the ability to use databases. In fact, Flutter communicates with the native system through plug-ins to operate the database.

Platform support

FLutter's SQLite plugin supports IOS, Android, and MacOS platforms

Use sqflite_common_ffi if you want to support Linux / Windows / DartVM

Web platform is not supported

Database operations are performed in the background of Android or ios

Use case

A simple notepad application that notepad_sqflite can run on iOS / Android / Windows / linux / Mac

Easy to use

Add dependency

In order to use the SQLite database, you first need to import two package, sqflite and path

Sqflite provides a wealth of classes and methods so that you can easily use the SQLite database.

Path provides a number of methods so that you can correctly define where the database is stored on disk.

Dependencies: sqflite: ^ 1.3.0 path: version number use

Import sqflite.dart

Import 'dart:async';import' package:path/path.dart';import 'package:sqflite/sqflite.dart'

Open the database

The SQLite database is the file in the file system. If it is a relative path, it is the path obtained by getDatabasesPath (), which is associated with the default database directory on Android and the documents directory on iOS.

Var db = await openDatabase ('my_db.db')

Many times we do not need to shut down the database manually when we use it, because the database will be closed when the program is closed. If you want to automatically release resources, you can use the following ways:

Await db.close (); execute the original SQL query

Use getDatabasesPath () to get the database location

Use the getDatabasesPath method in sqflite package and the join method in path package to define the path to the database. Using the join method in the path package is a best practice to ensure that the paths of each platform are correct.

Var databasesPath = await getDatabasesPath (); String path = join (databasesPath, 'demo.db')

Open the database:

Database database = await openDatabase (path, version: 1, onCreate: (Database db, int version) async {/ / create table await db.execute ('CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)');})

Increase:

Insert several pieces of data into a table in a transaction

Await database.transaction ((txn) async {int id1 = await txn.rawInsert ('INSERT INTO Test (name, value, num) VALUES ("some name", 1234, 456.789)'); print ('inserted1: $id1'); int id2 = await txn.rawInsert (' INSERT INTO Test (name, value, num) VALUES), ['another name', 12345678, 3.1416]); print (' inserted2: $id2');})

Delete:

Delete a piece of data from the table

Count = await database .rawDelete ('DELETE FROM Test WHERE name =?', ['another name'])

Change:

Modify the data in the table

Int count = await database.rawUpdate ('UPDATE Test SET name =?, value =? WHERE name =?, [' updated name', '9876,' some name']); print ('updated: $count')

Check:

Query the data in the table

/ / Get the recordsList list = await database.rawQuery ('SELECT * FROM Test'); List expectedList = [{' name': 'updated name',' id': 1, 'value': 9876,' num': 456.789}, {'name':' another name', 'id': 2,' value': 12345678, 'num': 3.1416}]; print (list); print (expectedList)

Total number of entries of data stored in the query table:

Count = Sqflite.firstIntValue (await database.rawQuery ('SELECT COUNT (*) FROM Test'))

Shut down the database:

Await database.close ()

Delete the database:

Await deleteDatabase (path); use the SQL assistant

Create fields and associated classes in the table

/ / Field final String tableTodo = 'todo';final String columnId =' _ id';final String columnTitle = 'title';final String columnDone =' done';// corresponding class class Todo {int id; String title; bool done; / / convert the current class to Map for external use Map toMap () {var map = {columnTitle: title, columnDone: done = = true? 1: 0} If (id! = null) {map [columnId] = id;} return map;} / / No-parameter construction Todo (); / / converts data of type map into the constructor of the current class object. Todo.fromMap (Map map) {id = map [columnId]; title = map [columnTitle]; done = map [columnDone] = = 1;}}

Use the above class to create and delete the database as well as add, delete, modify and query the data.

Class TodoProvider {Database db; Future open (String path) async {db = await openDatabase (path, version: 1, onCreate: (Database db, int version) async {await db.execute (''create table $tableTodo ($columnId integer primary key autoincrement, $columnTitle text not null, $columnDone integer not null)');}) } / insert a piece of data into the table and, if it has already been inserted, replace the previous one. Future insert (Todo todo) async {todo.id = await db.insert (tableTodo, todo.toMap (), conflictAlgorithm: ConflictAlgorithm.replace,); return todo;} Future getTodo (int id) async {List maps = await db.query (tableTodo, columns: [columnId, columnDone, columnTitle], where:'$columnId =?', whereArgs: [id]); if (maps.length > 0) {return Todo.fromMap (maps.first) } return null;} Future delete (int id) async {return await db.delete (tableTodo, where:'$columnId =?, whereArgs: [id]);} Future update (Todo todo) async {return await db.update (tableTodo, todo.toMap (), where:'$columnId =?', whereArgs: [todo.id]);} Future close () async = > db.close ();}

"=" queries all data in the table:

List records = await db.query ('my_table')

Get the first piece of data in the result:

Map mapRead = records.first

The Map in the list of query results above is read-only. Modifying this data will throw an exception.

MapRead ['my_column'] = 1bot / Crash... `mapRead` is read-only

Create a copy of map and modify the fields in it

/ / create a copy of map based on the map above Map map = Map.from (mapRead); / / modify the field value map ['my_column'] = 1 stored in this copy in memory

Put the queried List

< map>

Data of type is converted to List

< Todo>

Type, so that we can use it happily.

/ / Convert the List

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 248

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report