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

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

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

如何使用 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;

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

相关推荐

Flutter状态管理之Provider数据共享的底层实现

#头条创作挑战赛#简介高级的Flutter工程师往往都是从最简单的架构开始研究学习,今天给大家带来的是Flutter中比较重要的状态管理框架Provider,也是每位Flutter开发者必学的框架。P...

字节跨平台框架 Lynx 开源:一个 Web 开发者的原生体验

...

flutter软件开发笔记17-isolate的机制作用

这个isolate,相当于其他编程中的线程,并行处理一些事件,让程序更加高效。用厨房做菜的比喻帮你理解Isolate,附完整可运行的代码示例:一isolate的比喻解释假设你是一个主厨(主Isol...

七爪源码:如何使用 SQLite 数据库在 Flutter 中保存大数据

SQLite是一个开源、零配置、自包含、独立的事务关系数据库引擎,旨在嵌入到应用程序中。sqfliteFlutter的SQLite插件。支持iOS、Android和MacOS。支持事务...

Flutter 实现多语言

本文同步本人掘金平台的文章:https://juejin.cn/post/7164571616314130469我们在处理跨国业务、跨地区(比如港澳台)业务的时候,需要针对当地的语言来做兼容。所以,我...

开始第一个Flet应用

Flet是基于Flutter的UI框架,但是我们不需要熟悉Flutter,也不需要会前端,只要具备Python面向对象编程基础就可以了。当然我本人是不会Flutter的,所以也没法对比Flet和Flu...

《史记微软UI框架轮回本纪》

微软者,乃美地西雅图之枭雄,曾持Windows以令诸侯。自庚午(1990)以降,数易UI之术,然其UI之框架兴也勃焉,其亡也忽焉。太史公观其轮回之迹,未尝不掷笔长叹:天命固难测,然微软UI之败,岂非自...

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

如何使用SharedPreferences?在Android中,你可以使用SharedPreferencesAPI来存储少量的键值对。在Flutter中,使用Shared_Pref...

Flutter——输入部件

上一节介绍了文本部件,用于显示文本。但是在我们进行日常软件开发过程中,经常是需要获取用户键入的内容,比如用户名、密码、性别、喜好等等。...

我用VS Code 开发工具来开发 自己的 Flutter 应用 工具快而轻

本文将与你一起回顾如何在VSCode里进行Flutter应用的开发。1.安装和配置根据编辑工具设定的指引来安装Dart和Flutter扩展(也叫做插件)。1.1更新扩展程序...

Flutter 结合 Dio 使用

#头条创作挑战赛#上一篇文章...

Flutter——路由

路由(Route)在移动开发中通常指页面(Page),这跟Web开发中单页应用的Route概念意义是相同的,Route在Android中通常指一个Activity,在iOS中指一个...

Flutter 实战经验(五):在 VS Code 里开发 Flutter 应用

本文将与你一起回顾如何在VSCode里进行Flutter应用的开发。1.安装和配置根据编辑工具设定的指引来安装Dart和Flutter扩展(也叫做插件)。1.1更新扩展程序扩...

Flutter 2 的Windows 开发试验

刚安装了flutter2.1dev版本,测试下很感觉兴趣的Windows开发当前flutter环境为(flutterdoctor):Doctorsummary(toseeallde...

基于flutter/dart仿抖音app实例

简介flutter_tiktok项目是基于flutter+dart+fijkplayer等技术开发的仿抖音短视频app实例。https://github.com/mjl0602/flutter_tik...