跳至正文内容
TursoDB.cn 独立社区 · MVCC 并发写与每 Agent 独立库实战 阅读解析 →
Turso Cloud SDK 开发套件 社区 SDK Flutter / Dart

Turso 快速入门(Flutter / Dart)

通过几个简单步骤,开始使用 Flutter 和 Dart 中的 libSQL 客户端

注意

此 SDK 由社区维护,可能未获得 Turso 官方支持,也可能未及时跟进最新功能。如需帮助和反馈,请加入 Discord 上的 #libsql-dart 频道。

在本 Flutter/Dart 快速入门中,我们将学习如何:

  • 获取数据库凭据
  • 安装 Flutter/Dart libSQL 客户端
  • 连接本地或远程 Turso 数据库
  • 使用 SQL 执行查询
  • 将更改同步到本地数据库(可选)

1. 获取数据库凭据

继续操作前,你需要一个现有数据库。如果没有,请创建一个。

获取数据库 URL:

turso db show --url <database-name>

获取数据库认证令牌:

turso db tokens create <database-name>

将凭据赋值给 .env 中的环境变量。

TURSO_DATABASE_URL=
TURSO_AUTH_TOKEN=
注意

你需要将这些值存储为环境变量。

2. 安装 libsql_dart

flutter pub add libsql_dart

3. 初始化

现在使用 LibsqlClient 构造函数连接本地或远程数据库:

嵌入式副本
final dir = await getApplicationCacheDirectory();
final path = '${dir.path}/local.db';

final client = LibsqlClient(path)
  ..authToken = '<TOKEN>'
  ..syncUrl = '<TURSO_OR_LIBSQL_URL>'
  ..syncIntervalSeconds = 5
  ..readYourWrites = true;
仅本地
final dir = await getApplicationCacheDirectory();
final path = '${dir.path}/local.db';

final client = LibsqlClient(path);
final client = LibsqlClient(":memory:");
仅远程
final client = LibsqlClient('<TURSO_OR_LIBSQL_URL>')
  ..authToken = '<TOKEN>';

4. 连接

await client.connect();

5. 执行

await client.execute("create table if not exists customers (id integer primary key, name text);");
await client.query("insert into customers(name) values ('John Doe')");
print(await client.query("select * from customers"));
await client.batch("""insert into customers (name) values ('Jane Doe'); insert into customers (name) values ('Jake Doe');""");
final statement = await client
	.prepare("select * from customers where id = ?");

await statement.query(positional: [1])
final tx = await client.transaction();

await tx
	.execute("update customers set name = 'John Noe' where id = 1");
await tx
	.execute("update customers set name = 'Jane Noe' where id = 2");
print(await tx
	.query("select * from customers where id = ?", positional: [1]));

await tx.commit();

如果你需要使用占位符来表示值,可以这样做:

final statement = await client
  .prepare("select * from customers where id = ?");

await statement.query(positional: [1])
final statement = await client
	.prepare("select * from customers where id = :id");

await statement.query(named: {"id": 1})

6. 同步(仅限嵌入式副本)

使用嵌入式副本时,你应在连接器上调用 sync(),以将本地数据库与主数据库同步。

await client.sync();
同步自官方 Turso 文档仓库 ( tursodatabase/turso-docs · MIT 开源协议) 查看官方原文 ↗
搜索
按 Esc 关闭 · 由 Pagefind 静态索引驱动