android vollery 如何执行多次查询_Android中的数据库和本地存储在Flutter中是怎样实现的...

如何使用 Shared Preferences?

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

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

6876097061d69570ed7d31918a496f2a.png

用法

要使用此插件,请在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 插件实现此功能。

6ec6cdd70677867750e95e50fad35d5e.png

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 getDatabasesPathvar databasesPath = await getDatabasesPath();String path = join(databasesPath, 'demo.db');// Delete the databaseawait deleteDatabase(path);// open the databaseDatabase 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 transactionawait database.transaction((txn) async { int id1 = await txn.rawInsert( 'INSERT INTO Test(name, value, num) VALUES("some name
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值