Skip to the page

Reference · SDKs

Dart & Flutter

Call your deployed queries through a generated Dart client, and use napalm_client for sessions, live streams, webhooks, uploads and search.

In the schema
—

Installation and generation#

Run napalm generate from your project folder after you write your query files. The SDKs overview covers the generated files and how deployed queries are called.

Session, live & upload runtime

Manages PKCE sign-in, causal Napalm-Bookmark headers, multiplexed SSE streams, local sync stores and resumable file uploads.

Generated deployed-query calls

napalm generate turns every .edgeql file in dbschema/queries into typed functions, live descriptors and reactive hooks or streams.

Generate into lib/napalm (napalm generate notes --lang dart -o lib/napalm) and wire up swagger_dart_code_generator with build_runner.

Install once
dart pub add chopper json_annotationdart pub add --dev build_runner chopper_generator json_serializable swagger_dart_code_generator
build.yaml
targets:  $default:    builders:      swagger_dart_code_generator:        options:          input_folder: "lib/napalm/"          output_folder: "lib/napalm/client/"
lib/main.dart
final napalm = NapalmClient(Uri.parse('https://<label>.napalmdata.com'), token: () => session);final db = Openapi.create(  baseUrl: Uri.parse('https://<label>.napalmdata.com'),  // Sends the caller's token as it stands now, and the session's bookmark.  httpClient: napalm.httpClient,); final found = await db.queryGetNotePost(  body: GetNoteRequest(query: Queries.getNote, variables: GetNoteVariables(id: id)),);

Sign-in#

SignIn (in napalm-client and napalm_client) wraps the project’s sign-in routes. Every method runs the PKCE flow for you by generating a verifier, sending its SHA-256 challenge, exchanging the authorization code at GET /sign-in/token and saving the resulting session in your chosen store. Pass the sign-in to NapalmClient, and every request carries the session, including typed calls made through napalm.fetch (or napalm.httpClient in Dart). When someone signs in, signs out or switches accounts, the client drops every live query’s rows immediately and re-subscribes as the new caller, so one person’s rows never linger on screen for the next person. (With a custom token function instead, call napalm.restart() whenever the bearer changes.)

lib/sign_in.dart
final signIn = SignIn(Uri.parse('https://<label>.napalmdata.com'), store: keychain, passkeys: devicePasskeys);final napalm = NapalmClient(Uri.parse('https://<label>.napalmdata.com'), signIn: signIn); await signIn.sendCode(email);            // emails a magic linkawait signIn.withCode(email, typedCode); // the session, kept in the store // A provider: open its page, then finish with the universal link your app is opened at.final back = Uri.parse('https://app.example.com/signed-in');await launchUrl(await signIn.providerUrl('builtin::oauth_google', redirectTo: back));await signIn.finish(openedAt);
Email and password
signUp, withPassword, verify, resendVerification, sendPasswordReset, resetPassword
OAuth and OpenID Connect
providerUrl to start, then finish on the provider’s return page (or deep link)
Magic links
sendCode, then withCode for a typed code or finish for a link
Passkeys
addPasskey, withPasskey. For a session a server keeps: begin on the server, passkeyCode or addPasskeyCode in the page and finish on the server
The session
session(), token, signOut(), signOutEverywhere(), pageToken() and onChange (TypeScript) or changes (Dart)

metadata() returns the app name, the brand and the enabled providers, so a sign-in page can render only the project’s sign-in options. A step that leaves the page (a provider, a magic link, a confirmation email) stores the step’s verifier. finish must run against the sign-in’s original store, or the call throws no_verifier. When the project requires verified addresses, signUp and addPasskey return no session until the address is confirmed.

Choose where the session lives with the store option. webStore() uses localStorage and follows a sign-in or sign-out made in another tab. memoryStore() lasts as long as the object. Any object with get and set also works, such as the Keychain or Keystore in a Flutter app. A session’s token lasts an hour and is renewed for you. A session that has ended or been signed out anywhere reads as signed out. In React, useSession(signIn) from napalm-client/react follows the session.

Passkeys use the browser’s navigator.credentials in TypeScript. On a phone, pass a passkeys library as the passkeys option. In Dart, pass a Passkeys implementation backed by your platform’s passkey plugin. Refusals throw NapalmError (NapalmException in Dart) with a stable code: no_identity_found for a wrong address or password, verification_required, user_already_registered, verification_failed for a wrong or spent one-time code and passkey_declined.

Live query streams#

Every read-only query file also generates a typed live subscription helper. NapalmClient multiplexes all active subscriptions in your app onto a single SSE connection to POST /subscribe and applies incremental row patches as transactions commit. See Live queries for wire protocol details.

Multiplexed SSE live queries

NapalmClient shares one POST /subscribe stream across every active query, applying commit-aligned id patches and dropping rows immediately on sign-out.

Persistent device sync stores

sync renders cached rows from IndexedDB or SQLite before the network answers, reconciles patches by id and resumes from the stored bookmark.

In Dart and Flutter (--lang dart), live.dart exposes a typed Stream for each read query.

lib/note_page.dart
final napalm = NapalmClient(Uri.parse('https://<label>.napalmdata.com'), token: () => session); Live.getNote(napalm, GetNoteVariables(id: noteId)).listen((note) => render(note.rows));

Rows on the device#

sync caches a deployed query’s rows in a local store on the device so views render immediately, even offline. The store records the rows’ bookmark, requests only the diff since that bookmark on reconnect and applies incoming patches by id (removing any cached row omitted from the current result IDs, or replacing the cache with a full result when the change log no longer covers that bookmark). When the signed-in user changes, the client clears every open sync store. Offline caches & reconnect sync builds an app on sync.

lib/notes.dart
import 'package:napalm_client/napalm_client.dart'; import 'napalm/client/openapi.models.swagger.dart';import 'services/sqflite_sync_store.dart'; // One store for each synced query, made once.final notesStore = SqfliteSyncStore(database, 'notes'); // The stored rows at once, then the project's. Cancel the subscription to stop.final notes = napalm    .sync(      const LiveQuery.deployed('listNotes'),      notesStore,      decode: (row) => ListNotesDataItem.fromJson(row as Map<String, dynamic>),    )    .listen((synced) => render(synced.rows, isStored: synced.isStored));

A SyncStore wraps your app’s database, and napalm_client adds no database dependency. The offline guide has a sqflite adapter. MemorySyncStore keeps rows in memory. Each SyncedRows event carries isStored, which stays true until the first live result arrives.

A count or another result without object ids is refused with ids_required. A refusal leaves the store unchanged. Every sync of one query with the same variables shares one subscription and one store.

Webhooks#

When you attach a webhook to a schema notify trigger, Napalm POSTs a signed payload whenever matching writes commit. Use readDelivery to verify the Napalm-Signature HMAC-SHA256 header over the raw request bytes in constant time and parse the typed delivery. The delivery carries a kind (ping, rows, gap or test), an id for idempotency, the event and a causal position.

lib/webhook.dart
final delivery = readDelivery(await request.read().expand((chunk) => chunk).toList(), request.headers, signingSecret);if (delivery.kind == 'ping') queue.add((event: delivery.event, position: delivery.position)); // In the background worker: advance the session bookmark before querying.napalm.reach(job.position);final found = await db.queryListUnsentOrdersPost(body: const ListUnsentOrdersRequest());

Acknowledge the webhook promptly with a 2xx status and run heavy work in a background queue. Unacknowledged deliveries retry with exponential backoff. Pass delivery.position to napalm.reach(...) so the worker’s read sees the exact commit that fired the webhook. The guarantee holds on a replica too.

The change log#

changes reads a branch’s committed rows from the change log through GET /changes, one page at a time. The caller’s access rules filter the rows. Each transaction’s rows carry a type, operation, id and values, and a gap marks each stretch the log cannot return. Start from a time with since, then pass each page’s next back as after. Delivery is at least once, so save the cursor after you handle a page, not before.

lib/sync.dart
await for (final page in napalm.changes(types: ['Order'], after: cursor, reach: delivery.position)) {  await warehouse.apply(page.items);  if (page.next case final next?) cursor = await saveCursor(next);}

With reach, the reader stops once the log reaches that position, waiting briefly if needed. Paired with a ping webhook, you can tail the log without polling by reading up to each ping’s position. Without reach, the reader drains all available entries and stops, which fits scheduled catch-up jobs. To have committed rows pushed directly instead, attach a service key to the webhook so it delivers rows in order.

File uploads#

A query that sets a file’s size returns a file_upload once. upload takes that descriptor and the bytes and runs the rest of the upload lifecycle. A small file goes up in one signed PUT straight to object storage. A large file goes up four parts at a time, and part URLs are fetched as needed. Then POST /uploads/complete checks the size and reads the format from the first bytes. A PUT the store did not answer is tried again. The file’s ready state joins the client’s session, so a read right after the upload sees the file.

A stopped large upload resumes at the same point. Each part is sent with its SHA-256 digest, which object storage records. Calling upload again with the same file_upload and the same file sends only the parts the store does not hold. Keep the file_upload you received until the upload finishes.

lib/upload.dart
final file = File(path);final added = await db.queryAddScanPost(  body: AddScanRequest(variables: AddScanVariables(name: name, size: await file.length())),);final facts = await napalm.upload(  added.body!.data.first.fileUpload,  UploadSource(await file.length(), file.openRead),  onProgress: (sent, total) => progress.value = sent / total,);

Bytes that a type’s rule refuses throw the rule’s message under not_accepted. The same file_upload accepts the right bytes until the descriptor expires. An UploadSource reads the file a stretch at a time, so a large file is never held whole.

Search and questions#

search calls POST /search to rank objects of one type by combined semantic and keyword relevance under the caller’s access rules. ask calls POST /ask, where a model synthesizes one EdgeQL statement for the question, runs it read-only as the caller and returns the rows alongside the statement. Both methods share the client’s session and causal bookmark.

lib/search.dart
final notes = await napalm.search('Note', 'plans for the launch', limit: 5, fields: ['title']);final found = await napalm.ask('Which of my notes mention the launch?');

Streamed action answers#

streamAction calls an action and reads the handler’s answer as a stream. The call yields each frame as it arrives with its event name, raw text and parsed JSON. A handler that answers JSON gives one frame named answer. An error frame ends the answer with a NapalmError (NapalmException in Dart), and a stream cut mid-flight ends with stream_ended. The stream’s bookmark merges into the client session so subsequent reads observe the handler’s writes.

lib/summary.dart
// Each frame of the action's answer as the frame arrives. Cancelling the subscription cuts the request.await for (final frame in napalm.streamAction('summarizeNote', variables: {'note': noteId})) {  if (frame.json case final String text) summary.write(text);}

Type a word or two to search every docs page.