㑈手机版
  • 首页
  • 维修信息
  • 英语学习
  • 人物介绍
  • 旅游攻略
  • 汽车知识
  • 电脑数码
  • 生活常识
首页 电脑数码

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

时间:2024-02-17 06:39:32  编辑:勤于奋老勤

如何使用 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;
  • 本文分类:电脑数码
  • 浏览次数:509 次浏览
  • 本文链接:https://www.deibaike.com/diannaoshuma/gzZP1qJN5B.html
  • 上一篇 > 磁盘内存不足怎么办,谁偷吃了你的内存?教你快速清理方案
  • 下一篇 > mate40可以扩展内存吗,手机内存扩展功能是鸡肋吗?
相关文章
  • 强力保险箱全国售后服务电话24小时人工服务热线
    强力保险箱全国售后服务电话24小时人工服务热线售后服务体系——以专业守护您的资产安全.强力保险箱全国售后服务电话24小时人工服务热线客服全国售后服务点热线400-605-8619一、强力保险箱全国售后服务电话24小时人工服务热线全周期保修服务标准保修政策新品购买后提供3年整机免[详细]
  • 杰宝大王保险柜售后服务全国热线故障预约电话
    杰宝大王保险柜售后服务全国热线故障预约电话故障原因及使用维护指南杰宝大王保险柜售后服务全国热线故障预约电话作为存放贵重物品的重要工具,其稳定性和安全性直接影响用户财产安全。然而,长期使用中可能出现故障,影响正常使用。本文将从常见故障原因、使用技巧及售后服务三方面展开分析,帮助用户延长杰宝大[详细]
  • 恒发保险柜全国24小时售后维修服务电话
    恒发保险柜全国24小时售后维修服务电话售后服务与故障维修全指南恒发保险柜全国24小时售后维修服务电话作为财产安全的重要保障工具,其售后服务与故障维修服务直接影响用户的使用体验和财产安全。恒发保险柜全国24小时售后维修服务电话服务内容、维修流程及售后服务的核心要点。恒发保险柜全国24小时[详细]
  • 彩月保险箱售后电话全国服务24小时400人工客服热线
    彩月保险箱售后电话全国服务24小时400人工客服热线售后维修服务指南及常见故障解决方案彩月保险箱售后电话全国服务24小时400人工客服热线全国各售后服务电话400-605-8619一、彩月保险箱售后电话全国服务24小时400人工客服热线售后维修服务流程服务预约彩月保险箱售后电话[详细]
  • 新宝塔保险箱全国各售后服务热线号码
    《新宝塔保险箱全国各售后服务热线号码故障处理与售后服务指南》,采用模块化结构便于阅读:新宝塔保险箱全国各售后服务热线号码售后网点全国各市售后服务电话400-605-8619一、新宝塔保险箱全国各售后服务热线号码常见故障类型解析无法正常开启原因:密码错误次数超限/电路板故障/机械[详细]
最新推荐
  • 强力保险箱全国售后服务电话24小时人工服务热线
  • 杰宝大王保险柜售后服务全国热线故障预约电话
  • 恒发保险柜全国24小时售后维修服务电话
  • 彩月保险箱售后电话全国服务24小时400人工客服热线
  • 新宝塔保险箱全国各售后服务热线号码
  • 多吉保险箱全国各市售后服务电话热线
  • 大一保险箱24小时全国各售后服
  • 驰球保险箱售后维修电话客服中心
  • 虎王保险柜维修-24小时全市区服务热线
  • 恒发保险柜全国24小时售后服务电话号码
热门推荐
  • 庐山的风景特色:自然之峰与文化之境
  • c盘的东西怎么清理 ?电脑c盘垃圾太多不知道怎么清理一招教你解决
  • 贵州三都县有什么旅游景点?3大传统村落,这里藏着不一样的水族风情
  • 居民医保异地就医怎么办理手续 ,哪些人适用?一文了解→
  • 汽车托运|车辆是如何装载托运的呢?
  • 你知道“get off your high horse的俚语 是什么意思吗?
  • 车保险保费上涨怎么算 走保险还是私了?次年保费涨多少?先报案不理赔”不算出险?
  • c盘temp清理? 电脑越用越卡怎么办?5个方法教你释放C盘空间,瞬间多出几个G
  • kick back俚语”不是踢回去!职场人士一定要懂!
  • 车险第三者二百万保费多少钱 ,买多少合适?老司机算笔账

网站内容来自网络,如有侵权请联系我们,立即删除!
Copyright © 得百科 琼ICP备2023010365号-2