百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT技术 > 正文

Android中的数据库和本地存储在Flutter中是怎样实现的

wptr33 2025-04-26 21:40 19 浏览

如何使用 Shared Preferences?

在 Android 中,你可以使用 SharedPreferences API 来存储少量的键值对。

在 Flutter 中,使用 Shared_Preferences 插件 实现此功能。这个插件同时包装了 Shared Preferences 和 NSUserDefaults(iOS 平台对应 API)的功能。

用法

要使用此插件,请在pubspec.yaml文件中添加shared_preferences为依赖项。

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
 runApp(MaterialApp(
 home: Scaffold(
 body: Center(
 child: RaisedButton(
 onPressed: _incrementCounter,
 child: Text('Increment Counter'),
 ),
 ),
 ),
 ));
}

_incrementCounter() async {
 SharedPreferences prefs = await SharedPreferences.getInstance();
 int counter = (prefs.getInt('counter') ?? 0) + 1;
 print('Pressed $counter times.');
 await prefs.setInt('counter', counter);
}

测试

您可以SharedPreferences通过运行以下代码在测试中填充初始值:

const MethodChannel('plugins.flutter.io/shared_preferences')
 .setMockMethodCallHandler((MethodCall methodCall) async {
 if (methodCall.method == 'getAll') {
 return {}; // set initial values here if desired
 }
 return null;
 });

在 Flutter 中如何使用 SQLite?

在 Android 中,你会使用 SQLite 来存储可以通过 SQL 进行查询的结构化数据。

在 Flutter 中,使用 SQFlite 插件实现此功能。

Flutter的 SQLite插件。同时支持iOS和Android。

  • 支持交易和批次
  • 打开期间自动版本管理
  • 插入/查询/更新/删除查询的助手
  • 在iOS和Android的后台线程中执行的数据库操作

入门

在flutter项目中添加依赖项:

dependencies:
 ...
 sqflite: ^1.1.7+1

用法示例

进口 sqflite.dart

打开数据库

SQLite数据库是文件系统中由路径标识的文件。如果是相对路径,则该路径相对于所获得的路径,该路径是getDatabasesPath()Android上的默认数据库目录和iOS上的documents目录。

var db = await openDatabase('my_db.db');

有一个基本的迁移机制可以处理打开期间的模式更改。

许多应用程序使用一个数据库,并且永远不需要关闭它(当应用程序终止时,它将关闭)。如果要释放资源,可以关闭数据库。

await db.close();

原始的SQL查询

演示代码执行原始SQL查询

// Get a location using getDatabasesPath
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'demo.db');

// Delete the database
await deleteDatabase(path);

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

// Insert some records 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');
});

// Update some record
int count = await database.rawUpdate(
 'UPDATE Test SET name = ?, VALUE = ? WHERE name = ?',
 ['updated name', '9876', 'some name']);
print('updated: $count');

// Get the records
List 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);
assert(const DeepCollectionEquality().equals(list, expectedList));

// Count the records
count = Sqflite
 .firstIntValue(await database.rawQuery('SELECT COUNT(*) FROM Test'));
assert(count == 2);

// Delete a record
count = await database
 .rawDelete('DELETE FROM Test WHERE name = ?', ['another name']);
assert(count == 1);

// Close the database
await database.close();

SQL助手

使用助手的示例

final String tableTodo = 'todo';
final String columnId = '_id';
final String columnTitle = 'title';
final String columnDone = 'done';

class Todo {
 int id;
 String title;
 bool done;

 Map toMap() {
 var map = {
 columnTitle: title,
 columnDone: done == true ? 1 : 0
 };
 if (id != null) {
 map[columnId] = id;
 }
 return map;
 }

 Todo();

 Todo.fromMap(Map map) {
 id = map[columnId];
 title = map[columnTitle];
 done = map[columnDone] == 1;
 }
}

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)
''');
 });
 }

 Future insert(Todo todo) async {
 todo.id = await db.insert(tableTodo, todo.toMap());
 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();
}

读取结果

假设有以下读取结果:

生成的地图项为只读

// get the first record
Map mapRead = records.first;
// Update it in memory...this will throw an exception
mapRead['my_column'] = 1;
// Crash... `mapRead` is read-only

如果要在内存中进行修改,则需要创建一个新地图:

// get the first record
Map map = Map.from(mapRead);
// Update it in memory now
map['my_column'] = 1;

好了,今天就写到这儿吧,欢迎大家喜欢,如果你觉得还行,麻烦点击关注,点击赞,点击分享哈。

相关推荐

台积电提出SRAM存内计算新方法,能效比可达89TOPS/W

芯东西(公众号:aichip001)编译|高歌编辑|云鹏芯东西3月16日消息,近期,台积电的研究人员在ISSCC2021会议上公布了一种改良的SRAM存储器阵列,该SRAM阵列采用22nm工...

Golang中如何判断两个slice是否相等?

在Golang中,要判断两个slice是否相等是不能直接使用==运算符的(==只能说明两个slice是否指向同一个底层数组)。如果两个slice的底层数组相同,但长度或容量不同...

JS入门基础知识(js基础知识总结笔记)

JS对象操作对象增删改查创建对象letobj={}新增属性obj.a=1修改属性obj.a='a'...

趣谈JS二进制:File、Blob、FileReader、ArrayBuffer、Base64

大家好,我是Echa。好久没跟粉丝们细聊JavaScript那点事了。做一名全栈工程师,JS基础还是要打牢,这样的话不管底层业务逻辑以及第三方框架怎么变化,都离不开基础。本文文章属于基础篇,阅读有点...

告别 substr() 和 substring()?更可靠的 JavaScript 字符串截取方法

JavaScript提供了三个主要的字符串截取方法:...

golang第九天,切片(slice)介绍(golang 切片作为参数)

什么是切片golang切片是对数组的抽象。go的数组长度不可改变,在特定场景中这样的集合就不太适用,go中提供了一种灵活,功能强悍的内置类型切片(“动态数组”),与数组相比切片的长度是不固定的,可以追...

Go语言零到一:数组(go struct数组)

引言...

你说你熟悉Slice,这道slice题你能答对吗?

每当你花费大量时间使用某种特定工具时,深入了解它并了解如何高效地使用它是很值得的。...

Python 3.14七大新特性总结:从t-string模板到GIL并发优化

Python3.14已进入测试阶段,根据PEP745发布计划,该版本已停止引入新功能,也就是说新特征就应该已经固定下来了。所以本文基于当前最新的beta2版本,深入分析了Python3.14中...

Python 幕后:Python导入import的工作原理

更多互联网精彩资讯、工作效率提升关注【飞鱼在浪屿】(日更新)Python最容易被误解的方面其中之一是import。...

Python元类实现自动化编程的正确姿势

元类是Python中用于创建类的类。通过元类机制,开发者可在运行时动态创建和修改类,为框架开发、设计模式实现和高级架构设计提供核心支持。在Python语言的高级特性中,元类占据着独特而重要的地位。作...

Python字符串详解与示例(python字符串类型及操作)

艾瑞巴蒂字符串的干货来了,字符串是程序中最常见的数据类型之一,用来表示数据文本,下面就来介绍下字符串的特性,操作和方法,和一些示例来吧道友:1.字符串的创建在python中字符串可以永单引号(...

恕我直言!你对Python里的import一无所知

文章来源:https://mp.weixin.qq.com/s/4WAOU_Lzy651IE-2zZSFfQ原文作者:写代码的明哥...

Python基础:字符串操作(python字符串的用法)

字符串是Python中最常用的数据类型之一,用于表示文本数据。我们将学习如何对字符串进行常见的操作,包括创建、访问、修改和处理字符串。通过掌握这些技巧,您将能够更好地处理和操作文本数据。让我们开始吧!...

Python 中 字符串处理的高效方法,不允许你还不知道

以下是Python中字符串处理的高效方法...