Turso Cloud SDK 開發套件 社群 SDK Flutter / Dart
Turso 快速入門 (Flutter / Dart)
使用 libSQL 用戶端,透過幾個簡單步驟開始使用 Flutter 與 Dart
注意
此 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 開源授權)
檢視官方原文 ↗