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 the database in Flutter

2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "how to use the database in Flutter". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use the database in Flutter.

In the process of Flutter development, we sometimes need to persist some data locally. Using sp file form can also solve the problem, but sometimes when the amount of data is large, it is obvious that our file form is not suitable. At this time, we need to use a database for storage. We know that there is a lightweight sqlite database provided by the system in the native, in the powerful ecological environment of Flutter. There is also a database plug-in sqflite: ^ 2.0.2 that can operate databases in Androud and iOS at the same time.

1. Create a database: here I'll take storing my search history as an example.

First import:

Import 'package:sqflite/sqflite.dart'

Here I have created a database helper class to prepare for future database updates, upgrades, etc.:

Code implementation: mainly encapsulates the acquisition of the class Database.

/ / the database help class class DbHelper {final String path = "laoli.db"; / / the database name is generally the same / / the table name in the database here is the table static final searchTab = "SearchHistory" where I saved the wrong history search record; / / the private construction DbHelper._ (); static DbHelper? _ instance; static DbHelper get instance = > _ getInstance (); factory DbHelper () {return instance } static DbHelper _ getInstance () {if (_ instance = = null) {_ instance = DbHelper._ ();} return _ instance?? DbHelper._ ();} / / the path / SQLite database stored by default in the database is the file identified by the path in the file system. In the case of relative, / this path is relative to the acquired path getDatabasesPath (), / Android default database directory, / iOS/MacOS documents directory. Future? _ db; Future? GetDb () {_ db? = _ initDb (); return _ db;} / / Guaranteed to be called only once. Make sure to call Future _ initDb () async only once {/ / this is where we really created the database vserion represents the version of the database, if the version changes / / Then db will call the onUpgrade method to update final db = await openDatabase (this.path, version: 1, onCreate: (db, version) {/ / Database creation completed / / create a table, a self-increment id, a textdb.execute ("create table $searchTab (id integer primary key autoincrement, name text not null)") }, onUpgrade: (db, oldV, newV) {/ / upgrade the database call / db database / oldV old version number / / newV new version number / / this method will not be called again after the upgrade is completed); return db;} / / close the database close () async {await _ db?.then ((value) = > value.close ());}}

In the java background development process, the database will certainly be layered design, this benefit can greatly improve the robustness of the code and reduce later maintenance costs in the process of use. Although we use the database in the mobile front end, compared with the background, I still suggest that we also carry out hierarchical processing of the database, although it can be achieved without layering. But it can also reduce our maintenance costs for code and good programming habits. Needless to say, next we need to create a dao layer that processes the data.

Here sqflite encapsulates some commonly used sql syntax, such as adding, deleting, changing and checking, so we don't need to write sql syntax. Here I briefly encapsulate the method of adding, deleting, changing and checking.

Specific code:

/ / data manipulation class class DbSearchHistoryDao {/ / add static insert (String text) {/ / deduplicated queryAll () .then ((value) {bool isAdd = true; for (var data in value) {if (data.name = = text) {isAdd = false; break) }} if (isAdd) {DbHelper.instance.getDb ()? .then ((value) = > value.insert (DbHelper.searchTab, DbSearchHotBean (name: text). ToJson (),);}}) } / delete all static deleteAll () {DbHelper.instance.getDb ()? .then ((value) = > value.delete (DbHelper.searchTab,)) } / / Update data static update (DbSearchHotBean dbSearchHotBean) {DbHelper.instance.getDb ()? .then (value) = > value.update (DbHelper.searchTab, dbSearchHotBean.toJson (), / / specific updated data where: "id =?" / / find the data to be updated through id, whereArgs: [dbSearchHotBean.id]) } / / check the specific entity class static Future getBean (String name) async {var db = await DbHelper.instance.getDb () through name; var maps = await db?.query (DbHelper.searchTab, columns: ['id','name'], / / get which fields of the entity class default all where:' name =?', / / through the name field whereArgs: [name] in the entity class) / / the value of the specific name limits the data if (mapsqualified null & & maps.length > 0) {return DbSearchHotBean.fromJson (maps.first);} return null;} / / check all all static Future queryAll () async {List list = [] Await DbHelper.instance .getDb ()? .then ((db) = > db.query (DbHelper.searchTab). Then ((value) {for (var data in value) {list.add (DbSearchHotBean.fromJson (data));}})); return list;}}

Entity class: although there is only one field, creating an entity class makes it easy to expand later.

Class DbSearchHotBean {int? Id; String? Name; / / search terms DbSearchHotBean ({this.id,required this.name}); DbSearchHotBean.fromJson (Map json) {id = json ['id']; name = json [' name'];} Map toJson () {var map = {}; map ['id'] = id?.toString (); map [' name'] = name? "; return map;}

The specific usage is very simple:

Add: DbSearchHistoryDao.insert ("search term")

Delete all: DbSearchHistoryDao.deleteAll ()

Change: for example, change water to fire, and the entity that finds water modifies name by adding id.

DbSearchHistoryDao.getBean ("water") .then ((value) {if (valueworthy null) {DbSearchHistoryDao.update (DbSearchHotBean (id: value.id,name: "fire"));}})

Check all: await DbSearchHistoryDao.queryAll ()

This is the end of the basic usage of the database. Of course, batch operations can be used for some operations, such as deleting specified data, batch modification, batch deletion and so on. Here, you can view the author's documentation if necessary. Link

Batch = db.batch (); batch.insert ('Test', {' name': 'item'}); batch.update (' Test', {'name':' new_item'}, where: 'name =?', whereArgs: ['item']); batch.delete (' Test', where: 'name =?', whereArgs: ['item']); results = await batch.commit () Thank you for your reading, the above is the content of "how to use the database in Flutter". After the study of this article, I believe you have a deeper understanding of how to use the database in Flutter, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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: 0

*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