Flutter SDK

Updated

The translatize_ota package reads the strings you publish with Delivery (CDN) into a Flutter app, so a text fix reaches running apps without a store release. It supports Android, iOS, macOS, Windows and Linux. Requires Dart 3.4 and Flutter 3.22 or newer.

Anything you publish is public – never put secrets in translations
Anyone who knows a distribution's URL can download its strings. Keep API keys, internal URLs and personal data out of every branch you publish.
Flutter web is not supported yet
This version does not support Flutter web. For a web app, use the @translatize/ota npm package instead.
Release status
The package is version 0.1.0 and is meant to be public on pub.dev. If flutter pub add can't find it yet, it hasn't been published. This page describes the 0.1.0 API.

Before you start

Create a distribution under Project Settings → Delivery (CDN) and publish a release, as described in Delivery (CDN). The package needs the distribution's public ID, the 22-character part of its manifest URL. In the app, Copy SDK snippet on the distribution card has a Flutter entry that fills it in.

Install

terminal
flutter pub add translatize_ota

Set it up and read strings

lib/main.dart
import 'package:flutter/material.dart';
import 'package:translatize_ota/translatize_ota.dart';

final ota = TranslatizeOta(
  distributionId: 'YOUR_DISTRIBUTION_ID',
  bundled: {
    'en': {
      'home': {'title': 'Welcome'},
    },
  },
);

Future<void> main() async {
  // optional: puts cached strings on the first frame
  await ota.load('en');
  runApp(const MyApp());
}

// anywhere in the app
final title = ota.translate('home.title', 'en') ?? 'Welcome';

cdnUrl defaults to https://cdn.translatize.com. Keys are dotted whether the distribution publishes nested or flat JSON, so {"home": {"title": "…"}} is home.title. Other options: store, httpClient, minRefreshMs (default 300000) and timeoutMs (default 3000). An empty distributionId stops with an assertion in debug builds; in release builds the app serves cached and bundled strings.

MemberWhat it does
translate(key, locale)The string, or null. Takes a language code as listed in the distribution, like de or pt-BR. Answers from memory at once.
load(locale)Reads the cache, then returns every string for the language. Only with neither a cache nor a bundle does it wait for one fetch; if that fails the result is empty.
loadCached(locale)Reads the cache and never waits on the network.
refresh([locale])Checks now, whatever the age of the cache. Resolves with the languages that got new strings. Without an argument it covers the languages used so far. Bundled languages wait until they are used, because every CDN request counts.
updatesA ValueListenable<OtaUpdate?> that changes when a language gets new strings.
delegateA LocalizationsDelegate, see gen_l10n.
dispose()Stops notifying and closes the HTTP client it created.

translate is exact: it doesn't try pt for pt-BR. Bundle your default language, because before the first download it is the only text you have.

Refresh and updates

  • Freshness. When the cache is older than minRefreshMs, a call to translate or load starts a background check. A failed attempt waits out the same interval, so an offline app doesn't retry on every rebuild. refresh() skips that wait.
  • Requests. The manifest is fetched with If-None-Match, and a language file only when its hash changed. A 304 saves the bytes, but it still counts as a delivery request.
  • Listeners. updates fires when strings actually change: a new release, or the cache arriving after translate already answered from the bundle. Call load first and that second case doesn't happen.
  • Order. Downloaded strings first, per key, then bundled ones. A key the release lacks still comes from bundled, or from your fallback.

Using it with gen_l10n

gen_l10n writes a class of compiled getters and methods. There is no lookup by key to intercept, so l10n.home_title always returns the string compiled into the app, and no package can change that. What this package gives you instead is a second lookup, by key, that you call with the generated value as the fallback.

lib/app.dart
ValueListenableBuilder<OtaUpdate?>(
  valueListenable: ota.updates,
  builder: (context, update, child) {
    return MaterialApp(
      localizationsDelegates: [
        ota.delegate,
        ...AppLocalizations.localizationsDelegates,
      ],
      supportedLocales: AppLocalizations.supportedLocales,
      home: const HomePage(),
    );
  },
);
lib/home_page.dart
final l10n = AppLocalizations.of(context)!;

Text(OtaLocalizations.of(context).text('home.title', fallback: l10n.home_title));

What it does

  • Reads the cache for the app's locale before the first frame. It never waits on the network, so a slow CDN can't hold the app back.
  • Returns the OTA value when the distribution has the key, and your generated string when it doesn't.
  • Looks a locale up from exact to general: pt-BR, then pt.
  • Reloads when new strings arrive, as long as ota.delegate is read inside a builder listening to ota.updates, as above. Without that builder, new strings appear the next time a widget rebuilds.

What it doesn't do

  • It doesn't touch your generated class. Only call sites that go through text() get OTA strings. Every other l10n.something stays compiled.
  • It doesn't fill placeholders. See Placeholders stay as stored.
  • It doesn't translate Material or Cupertino widgets such as date pickers.
  • It doesn't add languages. supportedLocales is fixed at build time.
  • It doesn't guess between codes. Locale('zh', 'TW') won't find zh-Hant.

Keys

text() takes the key as it is in Translatize. An ARB export replaces dots with underscores because ARB keys become Dart names, so home.title in Translatize is home_title in your ARB file and in l10n:

Dart
strings.text('home.title', fallback: l10n.home_title)

Without the delegate in place, OtaLocalizations.of asserts in debug builds and returns the fallback in release builds.

Placeholders stay as stored

Values are returned exactly as stored. There is no formatting engine, so your app keeps its platform format, whether that is %@, %1$s or ICU.

That matters with gen_l10n, whose methods fill placeholders in for you, while an OTA value arrives with them still in it:

Dart
// "Hello {name}" in ARB, l10n.greeting(name) in Dart
strings
    .text('greeting', fallback: l10n.greeting(name))
    .replaceAll('{name}', name);

If the OTA value is used, replaceAll fills it in. If the fallback is used, it is already filled in and replaceAll finds nothing. Leave ICU plural and select messages on the generated method. An OTA value for one reaches the user as raw {count, plural, …} text.

What's cached, and where

Strings live in the application support directory, in translatize_ota/, one file per distribution and language. Each holds the hash, the strings and the fetch time. Writes are atomic and a corrupt file counts as no cache. To keep them elsewhere, pass any OtaStore:

Dart
class PrefsStore implements OtaStore {
  PrefsStore(this.prefs);

  final SharedPreferences prefs;

  @override
  Future<String?> read(String key) async => prefs.getString(key);

  @override
  Future<void> write(String key, String value) async {
    await prefs.setString(key, value);
  }
}

To test your app, pass store: MemoryOtaStore() and a MockClient from package:http/testing.dart as httpClient; no platform channel or network is involved.

When the CDN says no, or isn't there

Nothing throws into the app. The current strings stay in place on every failure.

CaseWhat happens
Hash mismatch, or not a JSON objectEvery file is checked against the sha256 in the manifest. A file that doesn't match, or isn't a JSON object, is dropped.
429No requests until Retry-After has passed (an hour if it's missing, a day at most). Strings keep being served.
404The distribution is disabled or unknown, so polling stops until the next launch. Strings keep being served.

See When the limit is reached for what causes them and Requests and blocks for how requests are counted.

Using iOS or Android? See the iOS SDK and the Android SDK.