siyak_flutter

Context-aware translation for Flutter, backed by Siyak.

An app is usually written in one language and shipped in several. siyak_flutter lets you keep the source string in the widget tree — Text('Settings') — and have the server learn its translation, in context, once. No key tables, no freeze, no Intl ceremony: a string you forget to translate is still a string you can read.

The target is any BCP-47 tag the Worker accepts — 'ar-EG', 'zh-Hans', 'tr', 'hi' — and the SDK tells you whether that language runs right to left, so direction follows the tag instead of hard-coding a guess.

dependencies:
  siyak_flutter: ^0.1.0

The one idea: t() is synchronous

final siyak = Siyak.init(
  apiKey: 'sk_live_…',
  endpoint: 'https://translate.yourapp.eg', // the URL on the API-key screen
  target: 'ar-EG',
);

Text(siyak.t('Settings'));   // returns instantly. Never throws. Never blocks.

t() returns the cached translation if there is one, and the source text if there is not — and queues the miss for a batched background fetch. That is the whole design: the first frame is your source string, the next is the translation.

Which raises the obvious question, and this is the part that matters:

The rebuild pattern

A cached-only getter is useless if nothing repaints when the translation arrives, so the client exposes two ValueNotifiers:

notifier type fires when
siyak.translationRevision ValueNotifier<int> a new translation enters the cache
siyak.lastError ValueNotifier<String?> a request fails (the Worker's error code), or recovers (null)

Pick whichever fits; they compose.

A. One listener for the whole screen. Simple, repaints the subtree, costs one setState:

class _HomeState extends State<Home> {
  final siyak = Siyak.shared;

  @override
  void initState() {
    super.initState();
    siyak.translationRevision.addListener(_repaint);
  }

  void _repaint() => setState(() {});

  @override
  void dispose() {
    siyak.translationRevision.removeListener(_repaint);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => Text(siak.t('Settings'));
}

B. Per-string, no StatefulWidget. ValueListenableBuilder rebuilds only itself, so a long list settles string by string instead of thrashing:

class TranslatedText extends StatelessWidget {
  const TranslatedText(this.source, {super.key, this.context});

  final String source;
  final String? context;

  @override
  Widget build(BuildContext buildContext) {
    final siyak = Siyak.shared;
    // `ctx`, not `context`: the shadowed name would otherwise hand the builder a
    // BuildContext where Siyak expects a translation context.
    return ValueListenableBuilder<int>(
      valueListenable: siyak.translationRevision,
      builder: (ctx, revision, child) => Text(siyak.t(source, context: context)),
    );
  }
}

C. Belt and braces — preload() then build. If you would rather the first frame were already translated, fetch the bundle before you render it:

await siyak.preload();                       // every approved string, one call
await siyak.warmUp(['Settings', 'Sign out'/*, …*/]);   // one batch, ≤20 per request

warmUp is what you call in initState of a screen you are navigating to. It never throws: a string the API could not deliver simply stays as the source.


Direction is a per-string property, not a per-app one

The trap: Text('Sign out') is LTR. Its translation, تسجيل الخروج, is RTL. If you keep an LTR Directionality around it, Arabic renders with the punctuation on the wrong edge, list tiles align wrong, and mixed content (بطاقة Visa •••• 4242) scrambles.

Two levels of fix:

// 1. Whole subtree: tell Flutter the script's base direction.
Directionality(
  textDirection: siyak.isRightToLeft ? TextDirection.rtl : TextDirection.ltr,
  child: MyArabicScreen(),
)

// 2. One string, in an otherwise LTR layout: override just that paragraph.
Text(
  siyak.t('Invoice #2041'),
  textDirection: TextDirection.rtl,
  textAlign: TextAlign.end,
)

siyak.isRightToLeft is isRtlTag(target): it reads the primary subtag, so ar, ar-EG, ar_EG are all RTL, and en is LTR. rtlLanguageTags is a small, documented set (ar, ckb, dv, fa, he, ps, sd, ug, ur, yi) — for the full Unicode list use intl's Bidi.

Rules that hold in practice:

  • Wrap the screen, not the app. A settings page in Arabic inside an app that keeps its LTR scaffold is fine; the Directionality boundary is what flips.
  • Never assume a translated string's direction from its source. A Latin brand name inside an Arabic sentence needs the paragraph to be RTL and the run to stay LTR — that is the Unicode bidi algorithm's job, so give Flutter the right base direction and let it resolve runs.
  • Icons that imply direction (back chevrons, Icons.arrow_back) must be mirrored; Flutter does that for icons flagged matchTextDirection, which is one more reason to set the direction on the subtree rather than patch Text widgets individually.

API

Siyak.init({
  required String apiKey,
  required String endpoint,
  required String target,
  String? source,
  String? context,
  int maxCacheEntries = 5000,
});

String  t(String text, {String? context});                 // cache-first, instant
Future<String> translate(String text, {String? context});   // awaits, falls back to text
Future<void> preload();                                     // GET /v1/strings
Future<void> warmUp(List<String> texts, {String? context}); // batch-fill, then render
void dispose();

Extras, all documented in the source: Siyak.shared, lastError, translationRevision, isRightToLeft, isParked, isBackingOff, usedChars, charLimit, requiresAttribution, badgeFor, resume, clearCachedTranslations, pendingCount.

init returns the instance; Siyak.shared returns the most recent one. Calling init again replaces it and leaves the previous instance inert (its queued work is dropped, its cache flushed, its notifiers left alive so an old widget cannot crash).

context is part of the string

حساب on a billing screen is account; on a profile screen it is profile. The server hashes text|target|context, so the cache does too. Set context once in init for a screen-wide default and override per call:

final siyak = Siyak.init(
  apiKey: key,
  endpoint: 'https://translate.yourapp.eg',
  target: 'ar-EG',
  context: 'checkout',
);
siyak.t('Total');                          // checkout's "المجموع"
siyak.t('Total', context: 'analytics');    // a different string, a different answer

Context must stay under 160 characters and free of < > (the server's rule); the SDK trims and strips them rather than taking a 400.


Why endpoint is required, and why you must not sprinkle it

A published APK and IPA have this URL compiled into the binary. When the Worker moves regions, changes hostnames, or splits into several deployments, the new host is free but the old one is not: it must 301 forever, because there is no way to reach the users of a build you no longer control.

That is also why this package ships no default host. A default would be a hostname somebody else could one day register, and every app that skipped the argument would be sending its API key and its source strings to that stranger. Siyak.init throws when endpoint is missing or is not an absolute http(s) URL, so the mistake surfaces at startup instead of on the way to a third party.

Write the address once in your own app — one constant or one --dart-define — and let every request path be /v1/… appended internally (_normalizeRoot): versioning is the escape hatch, and the prefix belongs to the URL, not to your code. The value to use is the one the dashboard prints on the API-key screen, which is the same string SIYAK serves publicly as api_base_url on /v1/site.

Override it when you want something else — a staging Worker, a regional mirror, or wrangler dev on your own laptop:

Siyak.init(
  apiKey: 'sk_test_…',
  target: 'ar-EG',
  endpoint: 'http://localhost:8787',
  allowInsecureEndpoint: true,   // plain http is refused otherwise
);

Auth is Authorization: Bearer <apiKey>, exactly as the Worker's apiKeyAuth expects (sk_live_/sk_test_ + 40 hex). The key ships inside your bundle, so use a sk_test_ key in debug builds and treat the live one like any other secret.


Cache

One JSON blob per key and language, written through shared_preferences:

key    : siyak:v1:sk_live_a1b2c3:ar-eg
value  : {"save|ar-EG|checkout":{"translated":"حفظ","status":"approved","badge":"Translated with Siyak"}, …}
  • The namespace prefix is the key's first 15 characters — the same prefix column the server stores — so the file identifies which key filled it without holding a secret.
  • Entry keys mirror the Worker's sourceHash: lowercased text|target|context, so Save and save are one entry and one charge.
  • Eviction is LRU-ish at maxCacheEntries (default 5000): a read re-inserts, so insertion order is recency and the front of the map goes first.
  • Writes are coalesced over persistDelay (800 ms) — a scrolling list does not hit preferences per string — and never happen before the blob has been read, so a cold start cannot delete its own history.
  • No platform channel? No problem. shared_preferences throws MissingPluginException in pure Dart and under flutter test without a registrar. The SDK catches that and keeps an InMemoryCacheStore. Inject your own CacheStore to test persistence either way.

Batching, limits, and what the SDK refuses to do

  • Misses from t() accumulate for batchDelay (120 ms — about one frame, so a whole screen's strings leave in one call) and are sent to POST /v1/translate/batch in chunks of 20, the server's MAX_BATCH_ITEMS. A full queue flushes immediately.
  • No string is ever sent longer than 500 characters. The Worker answers a longer one with 400 text exceeds 500 characters, so the SDK truncates and logs once per session. Long copy belongs in a localized asset, not in t().
  • Requests time out at requestTimeout (12 s), treated as a network failure.

Errors

HTTP error typed exception what the SDK does
401 invalid_api_key InvalidApiKeyException source text; lastError = 'invalid_api_key'; 30 s pause
402 quota_exceeded QuotaExceededException source text; parks for the session
403 origin_not_allowed OriginNotAllowedException source text; 30 s pause (native clients have no Origin, so this is rare)
429 rate_limited RateLimitedException source text; parks for the session, keeps retryAfterSeconds
500 internal_error SiyakException source text; 30 s pause
503 backend_unavailable BackendUnavailableException source text; 30 s pause
— socket/DNS/timeout SiyakNetworkException source text; 30 s pause

Parked means: no further requests at all until you call siyak.resume() or restart the app. t() keeps serving the cache and the source text, and queued misses are resolved with the source instead of being retried later.

402 and 429 are the two codes where retrying is provably useless — the month is spent, or the minute is — so a phone on metered 4G must not discover that by uploading a request loop. Everything transient gets a transientBackoff pause (30 s) instead of a park, because a model cold start ends on its own. translate() ignores both: if a human tapped something, it gets one real attempt.

Per-item failures inside a batch response ({items:[{status:"error", error:"quota_exceeded"}]}) are handled the same way, and a short items[] is read as "the server stopped paying" — the Worker breaks its loop on quota, so the remaining strings simply stay as the source.


Free plan attribution

On the free plan the Worker returns badge: "Translated with Siyak" alongside the translation. siyak.requiresAttribution turns true as soon as one arrives, and siyak.badgeFor('Settings') reads it back. Put it on an about screen; the plan upgrade removes it.


Testing

import 'package:http/http.dart' show Response;
import 'package:http/testing.dart';
import 'package:siyak_flutter/siyak_flutter.dart';

test('a miss paints the source, the batch fills it, the cache answers', () async {
  final siyak = Siyak.init(
    apiKey: 'sk_test_${'0' * 40}',
    endpoint: 'http://localhost:8787',
    allowInsecureEndpoint: true,
    target: 'ar',
    cacheStore: InMemoryCacheStore(),   // no platform channel needed
    httpClient: MockClient((request) async {
      if (request.url.path.endsWith('/translate/batch')) {
        // `input` has to echo the text exactly as sent: the SDK keeps the case of
        // the string it asked about, and drops a row whose echo disagrees rather
        // than risk painting the wrong string on the wrong key.
        return Response(
          '{"items":[{"input":"Save","output":"حفظ","status":"approved"}],'
          '"usage":{"used":4,"limit":15000,"month":"2026-10"}}',
          200,
          headers: {'content-type': 'application/json'},
        );
      }
      return Response('{"error":"quota_exceeded","used":15000,"limit":15000}', 402);
    }),
    batchDelay: Duration.zero,
  );

  expect(siyak.t('Save'), 'Save');   // queued, and the frame still paints now
  await siyak.warmUp(['Save']);     // one awaited batch
  expect(siyak.t('Save'), 'حفظ');    // cache hit: no second request
  expect(siyak.usedChars, 4);

  expect(await siyak.translate('Sign out'), 'Sign out');  // 402 falls back…
  expect(siyak.isParked, true);                            // …and the session parks
  expect(siyak.lastError.value, 'quota_exceeded');
  expect(siyak.pendingCount, 0);

  siyak.dispose();                  // stops timers, or `flutter test` hangs
});

translationRevision, pendingCount and lastError are the handles a test needs; everything else the SDK knows it can assert through the fake client. Add flutter_test (from the Flutter SDK) to your dev_dependencies for test(...).

translationRevision, pendingCount and lastError are the handles a test needs; everything else the SDK knows it can assert through the fake client.


Server quirks worth knowing

Read from worker/src, because the Worker is the contract:

  • source overrides the project, per request. When it is a valid tag the Worker uses it for the model call; omitted means fall back to project.source_lang. It does not mutate the project.
  • GET /v1/strings carries no context. The bundle is a source_text → translated_text map, so preload() can only fill context-free lookups; t(text, context: …) still hits the API. It also deduplicates by source text, and the map keeps the last row of order=status.asc, so translation_status's label order ('pending', 'approved') is what puts an approved row on top of machine output. The SDK still refuses to overwrite a cached entry from the bundle.
  • Batch results are positional. Rows carry index, input, output, origin and status, but not context, so the SDK maps by index and drops a row whose input disagrees with what was sent rather than risk painting one screen's string onto another's. A short items[] means the server stopped on quota_exceeded, not that rows moved.
  • Oversize text is rejected, not truncated. Hence the client-side clamp.

Development

analysis_options.yaml is flutter_lints plus strict-casts — every value that crosses the wire is narrowed with an explicit is/as, because a silent dynamic cast is how a server-side schema change becomes a crash in someone's build method. Run dart format . and flutter analyze before publishing, and keep example/lib/main.dart buildable: it is the documentation most users actually read.

License

MIT — see LICENSE.

Libraries

siyak_flutter
SIYAK — context-aware translation for Flutter apps.