Guides · Frameworks
Flutter
Build a Flutter app that signs people in through the system browser, keeps live queries active across the app lifecycle and resumes large uploads.
- In the schema
ext::files::File
What you’ll build#
This page builds a Flutter app that signs people in through iOS Keychain or Android Keystore, keeps document scans live across foreground transitions, caches permitted rows in local SQLite for offline cold launches and streams resumable multipart uploads straight from disk. The app pairs napalm_client with the typed Chopper services and Live.* streams generated by napalm generate.
Every query and offline sync runs under your schema’s policies inside PostgreSQL, so a device caches and displays only rows the signed-in person may read.
Lifecycle-aware Flutter viewport
Generated Chopper services and Live.* streams pause sockets in the background and resume from napalm.bookmark on foreground transitions.
Keychain & Keystore bearer sessions
KeychainStore persists PKCE bearer sessions across cold launches while local sqflite mirrors serve cached rows offline.
Before you start#
Start from a project with deployed queries and at least one sign-in method enabled. Your first app sets up that project in five commands.
Generate and wire up the client#
Push your named EdgeQL queries and generate typed Dart models, Chopper request methods and Live.* streams.
napalm queries push notesnapalm generate notes --deployed --lang dart -o lib/napalmdart run build_runner build --delete-conflicting-outputsThree objects coordinate every call. SignIn stores the active session in Keychain on iOS or Keystore on Android. NapalmClient attaches the bearer token, tracks Napalm-Bookmark and multiplexes SSE streams. Passing napalm.httpClient to the generated Openapi client ensures every mutation and read shares the session and reads back recent writes on replicas.
// lib/services/napalm_service.dartimport 'package:flutter_secure_storage/flutter_secure_storage.dart';import 'package:napalm_client/napalm_client.dart'; import '../napalm/client/openapi.swagger.dart'; /// Persists the active session and PKCE verifier in Keychain on iOS and Keystore on Android.class KeychainStore implements SignInStore { const KeychainStore(this._storage); final FlutterSecureStorage _storage; @override Future<String?> get(String key) => _storage.read(key: 'napalm.$key'); @override Future<void> set(String key, String? value) => value == null ? _storage.delete(key: 'napalm.$key') : _storage.write(key: 'napalm.$key', value: value);} class NapalmService { NapalmService(Uri address) : signIn = SignIn(address, store: const KeychainStore(FlutterSecureStorage())) { // Attaches the session to every request and restarts live streams when the caller changes. napalm = NapalmClient(address, signIn: signIn); // Routes generated Chopper calls through napalm.httpClient so calls share the bookmark. db = Openapi.create(baseUrl: address, httpClient: napalm.httpClient); } final SignIn signIn; late final NapalmClient napalm; late final Openapi db; void dispose() { napalm.close(); signIn.close(); }}Sign people in#
Project sign-in returns a bearer session token rather than a browser cookie, so Flutter apps never embed a web view. Password and magic-link flows run over plain HTTPS. OAuth providers open the system browser and return to your app’s reverse-DNS callback scheme or Universal / App Link. Register the callback with napalm sign-in set notes --redirect com.example.notes:/. The allowlist rejects single-word schemes without a dot such as notes://.
// lib/services/sign_in_flows.dartimport 'package:flutter_web_auth_2/flutter_web_auth_2.dart';import 'package:napalm_client/napalm_client.dart'; /// Reverse-DNS callback scheme registered in Info.plist, AndroidManifest.xml and napalm sign-in set.final _redirectTo = Uri.parse('com.example.notes://signed-in'); /// Opens an OAuth provider from signIn.metadata(), such as builtin::oauth_google, in the system browser.Future<Session?> signInWith(SignIn signIn, String provider) async { final url = await signIn.providerUrl(provider, redirectTo: _redirectTo); // Uses ASWebAuthenticationSession on iOS and Custom Tabs on Android rather than a web view. final returned = await FlutterWebAuth2.authenticate(url: '$url', callbackUrlScheme: _redirectTo.scheme); // Exchanges the returned authorization code with the PKCE verifier kept in KeychainStore. return signIn.finish(Uri.parse(returned));} /// Password sign-in completes over HTTPS without opening a browser.Future<Session> signInWithPassword(SignIn signIn, String email, String password) => signIn.withPassword(email, password); /// Magic-link sign-in sends a six-digit code and exchanges the code in the app.Future<void> sendCode(SignIn signIn, String email) => signIn.sendCode(email); Future<Session> enterCode(SignIn signIn, String email, String code) => signIn.withCode(email, code);Every sign-in flow writes the resulting session to KeychainStore and emits on signIn.changes, so a single root widget can switch between the authenticated app and the sign-in screen. Calling signIn.signOut() clears secure storage and notifies the same stream.
// lib/app.dartimport 'package:flutter/widgets.dart';import 'package:napalm_client/napalm_client.dart'; /// Switches between the authenticated app and the sign-in screen whenever the session changes.class SignedIn extends StatelessWidget { const SignedIn({super.key, required this.signIn, required this.app, required this.signInPage}); final SignIn signIn; final Widget app; final Widget signInPage; @override Widget build(BuildContext context) => FutureBuilder( // Loads the persisted session from Keychain or Keystore on cold launch. future: signIn.session(), builder: (context, kept) => StreamBuilder( // Emits every subsequent sign-in and sign-out event. stream: signIn.changes, initialData: kept.data, builder: (context, session) => kept.connectionState != ConnectionState.done ? const SizedBox.shrink() : session.data == null ? signInPage : app, ), );}Sign-in for your app covers sign-up, email verification, password resets and session lifetimes using identical method names.
Passkeys#
Because Dart packages delegate platform credential prompts to native plugins, pass SignIn a Passkeys adapter wrapping your chosen passkeys plugin. Project passkeys belong to one web origin, which iOS apps share via Associated Domains. Android binds native app passkeys to the APK signing key rather than the web origin, so Android passkeys are not yet supported.
// lib/services/passkeys.dartimport 'package:napalm_client/napalm_client.dart'; /// Bridges WebAuthn JSON options and credentials to your platform passkeys plugin.class DevicePasskeys implements Passkeys { const DevicePasskeys({required this.onCreate, required this.onGet}); final Future<Map<String, Object?>> Function(Map<String, Object?> options) onCreate; final Future<Map<String, Object?>> Function(Map<String, Object?> options) onGet; @override Future<Map<String, Object?>> create(Map<String, Object?> options) => onCreate(options); @override Future<Map<String, Object?>> get(Map<String, Object?> options) => onGet(options);} /// Pass DevicePasskeys into SignIn(address, store: store, passkeys: devicePasskeys):Future<Session> signInWithPasskey(SignIn signIn, String email) => signIn.withPasskey(email);Keep live queries across the app’s lifecycle#
Mobile operating systems pause background sockets, iOS reclaims open TCP streams seconds after an app leaves the screen and cellular handoffs from Wi-Fi to 5G drop idle connections. Pairing NapalmClient with Flutter’s AppLifecycleListener handles all three transitions cleanly.
// lib/pages/scans_page.dartimport 'dart:async';import 'package:flutter/widgets.dart';import 'package:napalm_client/napalm_client.dart'; import '../napalm/live.dart';import '../napalm/client/openapi.models.swagger.dart'; class ScansFeedController extends ChangeNotifier { ScansFeedController(this.napalm) { _lifecycle = AppLifecycleListener( onHide: _pauseStream, onShow: _resumeStream, ); _resumeStream(); } final NapalmClient napalm; late final AppLifecycleListener _lifecycle; StreamSubscription<LiveRows<ListScansDataItem>>? _sub; List<ListScansDataItem> scans = const []; void _resumeStream() { if (_sub != null) return; // Reconnects with napalm.bookmark so foreground snapshots never regress behind visible rows. _sub = Live.listScans(napalm).listen((snapshot) { scans = snapshot.rows; notifyListeners(); }); } void _pauseStream() { // Cancelling the final subscription closes the SSE socket while keeping rows and bookmark in RAM. _sub?.cancel(); _sub = null; } @override void dispose() { _pauseStream(); _lifecycle.dispose(); super.dispose(); }}- 35-second watchdog
- Napalm sends an SSE
heartbeatframe every 15 seconds. When cellular packet loss stalls a socket pastheartbeatTimeout(default 35 s),NapalmClientcloses the dead connection and reconnects with jittered backoff (500 ms up to 30 s). - Resume position
- Every SSE frame advances
napalm.bookmark. On foregrounding,_resumeStream()opens/subscribewith"lsn": napalm.bookmarkso the fresh snapshot never regresses behind the rows already on screen. - Zero idle wakeups
- Cancelling the last active
StreamSubscriptioninonHidecloses the underlying HTTP stream automatically so the radio sleeps in the background.
Cache rows offline with SQLite#
napalm.sync keeps the rows of listScans in the sqflite store from Offline caches & reconnect sync. A list renders the stored rows at once when a person opens the app in an elevator or airplane. On reconnect, the project sends only the changes since the stored bookmark rather than the whole list. Clear the store in signIn.changes so signing out wipes the rows from the device.
// lib/services/local_scans_mirror.dartimport 'dart:async';import 'package:napalm_client/napalm_client.dart';import 'package:sqflite/sqflite.dart'; import '../napalm/client/openapi.models.swagger.dart';import 'sqflite_sync_store.dart'; class LocalScansMirror { LocalScansMirror({required Database db, required this.napalm, required SignIn signIn}) : store = SqfliteSyncStore(db, 'scans') { // An open sync clears the store when the person changes. Clearing here covers a store no page holds open. _authSub = signIn.changes.listen((session) { if (session == null) unawaited(store.clear()); }); } final SqfliteSyncStore store; final NapalmClient napalm; StreamSubscription<Session?>? _authSub; /// The stored rows at once, then the changes since their bookmark. Every step lands in SQLite too. Stream<SyncedRows<ListScansDataItem>> scans() => napalm.sync( const LiveQuery.deployed('listScans'), store, decode: (row) => ListScansDataItem.fromJson(row as Map<String, dynamic>), ); Future<void> dispose() async => _authSub?.cancel();}To capture offline creates and edits in a durable queue with idempotent UUIDs and version conflict checks, follow the schema and outbox design in Offline caches & reconnect sync.
Upload large files#
Mobile camera videos and multi-page document scans often run 50 to 500 MiB and drop mid-flight in subways. Extending ext::files::File on your schema type adds direct-to-storage resumable uploads that stream from disk without loading the file into the Dart heap.
using extension auth;using extension files;using extension napalm;using future simple_scoping; module default { global caller := global ext::auth::ClientTokenIdentity; type Scan extending ext::files::File { required owner: ext::auth::Identity; constraint expression on (std::contains([ext::files::Format.Pdf], .file_format)) { errmessage := 'a PDF is required'; }; access policy owner_has_full_access allow all using (.owner ?= global caller); } type Avatar extending ext::files::File { overloaded required file_is_public: bool { default := true; }; required owner: ext::auth::Identity { constraint exclusive; }; constraint expression on (std::contains( [ext::files::Format.Png, ext::files::Format.Jpeg, ext::files::Format.Webp], .file_format)) { errmessage := 'an image is required'; }; access policy anyone_can_see allow select; access policy owner_can_change allow insert, update, delete using (.owner ?= global caller); }}select (insert Scan { owner := global caller, file_name := <str>$name, file_size := <int64>$size,}) { id, file_upload }// lib/services/scan_uploader.dartimport 'dart:convert';import 'dart:io'; import 'package:flutter_secure_storage/flutter_secure_storage.dart';import 'package:napalm_client/napalm_client.dart'; import '../napalm/client/openapi.swagger.dart'; Future<UploadFacts> uploadLargePdf({ required NapalmClient napalm, required Openapi db, required FlutterSecureStorage storage, required File file, required void Function(double fraction) onProgress,}) async { final cacheKey = 'pending_upload:${file.path}'; final length = await file.length(); // Reuse a persisted file_upload plan when an earlier cellular attempt dropped mid-transfer. Map<String, Object?>? uploadPlan; final savedJson = await storage.read(key: cacheKey); if (savedJson != null) { uploadPlan = (jsonDecode(savedJson) as Map<String, dynamic>).cast<String, Object?>(); } else { final created = await db.queryAddScanPost( body: AddScanRequest( variables: AddScanVariables(name: file.uri.pathSegments.last, size: length), ), ); uploadPlan = (created.body!.data.first.fileUpload as Map<String, dynamic>).cast<String, Object?>(); await storage.write(key: cacheKey, value: jsonEncode(uploadPlan)); } try { // Streams byte ranges via file.openRead without loading the whole PDF into memory. // Hashes 16 parts per window and skips parts already stored in object storage. final facts = await napalm.upload( uploadPlan, UploadSource(length, file.openRead), onProgress: (sent, total) => onProgress(sent / total), ); await storage.delete(key: cacheKey); return facts; } on NapalmException catch (error) { if (error.code == 'expired_upload') { // Upload session expired; clear the cached plan so the next retry opens a fresh token. await storage.delete(key: cacheKey); } rethrow; }}How a multipart upload resumes#
- Bounded RAM
UploadSource(length, file.openRead)reads one byte range (start..end) at a time from disk and keeps a 500 MiB video out of mobile memory.- 16-part SHA-256 windows
- For multipart files,
napalm.uploadhashes 16 parts per window and callsPOST /uploads/partswithstored: true. Parts whose SHA-256 digest already matches object storage are skipped and credited toonProgress. - 4x parallel part PUTs
- Missing parts upload four at a time directly to object storage with automatic per-PUT retry on transient
5xx,429or socket drops, followed byPOST /uploads/complete. - Immediate read visibility
POST /uploads/completereturns an updatedNapalm-Bookmark, whichnapalmstores so a follow-upfile_urlquery seesfile_status = Readyon any replica.
Handle upload and session errors#
| NapalmException.code | Cause | Recovery |
|---|---|---|
not_accepted | Magic-byte inspection or schema constraint rejected the uploaded file (such as a PNG renamed .pdf uploaded to Scan). | RecoveryDisplay error.message (your schema constraint’s errmessage, such as "a PDF is required"). Reuse the upload plan for a valid replacement of the same byte size or set file_size again. |
size_mismatch / | Uploaded byte count differed from the declared file_size, or sniffed magic bytes contradicted an explicit format expectation. | RecoveryRe-stat await file.length(), run your mutation setting file_size to obtain a fresh file_upload plan and retry. |
parts_incomplete | Connection dropped before all multipart chunks completed. | RecoveryKeep the persisted file_upload JSON and retry napalm.upload(...) when connectivity returns so already-stored parts are skipped. |
expired_upload | The presigned upload session aged past the expires timestamp. | RecoveryDelete the cached file_upload plan and run your update or insert query setting file_size again to obtain a fresh upload token. |
invalid_session | The user’s session expired or was revoked (!error.isRetryable). | RecoveryNapalmClient halts retries. Call signIn.signOut() so SignedIn switches back to the sign-in screen. |
Check the app#
Run flutter run on a physical phone or simulator.
Sign in and relaunch in airplane mode
Sign in while online so
KeychainStoresaves the session andLocalScansMirrorpopulates SQLite. Stop the app, enable airplane mode and launch again. Cached scans appear immediately without a sign-in screen.Background the app and add a scan from another device
Disable airplane mode, move the Flutter app to the background, insert a scan elsewhere and foreground the app. The resumed stream sends
napalm.bookmarkand renders the new scan without stale flicker.Drop connectivity halfway through a large PDF upload
napalm.uploadthrowsparts_incomplete. Restore the network and calluploadLargePdfagain. Stored chunks are skipped and progress continues from the interruption point.Sign out
Call
signIn.signOut().LocalScansMirrordeletescached_scans, andsignIn.changesswitches the root widget back to the sign-in screen.
Next steps#
- Offline caches & reconnect sync
- Add an offline SQLite outbox with client mutation UUIDs, row versions and conflict handling.
- Dart & Flutter SDK
- Reference every
napalm_clientclass, stream helper, search call and generated Chopper option. - Files, media & document search
- Extract uploaded PDFs in background jobs and run cited hybrid search under workspace rules.