---
title: Localization
description: Translate widget text and the widget gallery entry.
---
> ## Documentation Index
> Fetch the complete documentation index at: https://docs.page/abausg/home_widget/llms.txt
> Use this file to discover all available pages before exploring further.

# Localization

Widgets can ship translated text and a translated gallery entry (the name and
description users see when adding the widget). Translations live in the
annotation; the generator regenerates every platform file from them on each
run, so you never hand-maintain string resources or `Localizable.xcstrings`
yourself.

## Setup

Add a `localization:` block. It supplies the default locale that every fallback
resolves to, and the locale set the generated Dart class is built from:

```dart
@HomeWidget(
  name: 'Localized Greeting',
  description: 'Greets you in your language',
  localization: HomeWidgetLocalization(
    defaultLocale: 'en',
    supportedLocales: ['en', 'de', 'pt-BR'],
    // 'en' omitted, so the base text stays the top-level name/description.
    name: {'de': 'Lokalisierte Begrüßung', 'pt-BR': 'Saudação Localizada'},
    description: {
      'de': 'Begrüßt dich in deiner Sprache',
      'pt-BR': 'Cumprimenta você no seu idioma',
    },
  ),
  widget: HWColumn(
    children: [
      HWText.localized({'en': 'Greeting', 'de': 'Begrüßung', 'pt-BR': 'Saudação'}),
      HWText(
        HWString.localized(
          'greeting',
          defaultTranslations: {'en': 'Hello', 'de': 'Hallo', 'pt-BR': 'Olá'},
        ),
      ),
    ],
  ),
)
class LocalizedGreeting {}
```

`localization:` is required as soon as any localized string appears.

## Two kinds of localized text

**`HWText.localized({...})`** is fixed at build time — no data field, not
changeable from Dart. It ships as a platform string resource (an Android
`<string>` resource, a `Localizable.xcstrings` entry on iOS) and is resolved by
the OS like any other app string, against the user's full preferred-language
list.

**`HWString.localized(key, defaultTranslations: {...})`** is a real data field.
The `defaultTranslations` are what ships; your app can override any locale at
runtime. Every locale is a **required** parameter, so adding one to
`supportedLocales` becomes a compile error in your app until it has been
translated:

```dart
await LocalizedGreetingHomeWidget.saveData(
  greeting: LocalizedGreetingHomeWidgetTranslations(
    en: 'Hi there',
    de: 'Hallo du',
    ptBR: 'Oi',
  ),
);
```

If your app already localizes with `flutter gen-l10n`, the values usually come
straight from your generated `AppLocalizations` — one lookup per locale:

```dart
await LocalizedGreetingHomeWidget.saveData(
  greeting: LocalizedGreetingHomeWidgetTranslations(
    en: lookupAppLocalizations(const Locale('en')).widgetGreeting(userName),
    de: lookupAppLocalizations(const Locale('de')).widgetGreeting(userName),
    ptBR: lookupAppLocalizations(
      const Locale('pt', 'BR'),
    ).widgetGreeting(userName),
  ),
);
```

(`lookupAppLocalizations` returns strings for an explicit locale, independent
of `BuildContext`.) Flutter's `Locale` takes language and country as
**separate** arguments — `Locale('pt', 'BR')`, not `Locale('pt-BR')`.

`HWString.localized` also takes `previewTranslations`, in the same shape as
`defaultTranslations` and validated by the same completeness rules — sample
text the widget gallery shows ahead of the shipped translations. See
[Previews](/generator/previews#localized-preview-translations).

Unlike a plain `HWString`, this one is resolved by the widget itself, at render
time, against the device's *entire* preferred-language list — a pt-PT device
gets `pt-BR` text rather than falling straight to the default locale. See [How a
locale is matched](#how-a-locale-is-matched). `deleteData(greeting: true)`
clears the override and falls back to the shipped `defaultTranslations`.

A key names exactly one field. Declaring `greeting` as both `HWString('greeting')`
and `HWString.localized('greeting')` — or twice with different translations, or
an `HWInt` with two different defaults — is a generator error naming the key,
since both declarations would generate the same property.

## How a locale is matched

`HWText.localized` and the gallery entry are platform string resources, so the
OS matches them. Everything the widget resolves itself — keyed strings and
localized JSON leaves — runs the same chain on Android, iOS and in the generated
Dart `resolve(tag)`:

1. The exact tag (`pt-PT`).
2. The tag with its last subtag dropped, repeatedly, down to the bare language
   (`zh-Hant-TW` → `zh-Hant` → `zh`).
3. Any entry sharing that language but carrying a different region or script
   (`pt-PT` → `pt-BR`). If several match, the lexicographically smallest key
   wins, so the choice is stable across runs.
4. The widget's default locale.

Steps 1–3 run for each entry of the device's preferred-language list in turn,
and only once the whole list is exhausted does step 4 apply — a device set to
`[de-AT, fr, en]` gets French rather than the default locale when `de` is not
translated.

On Android the device tags come from `toLanguageTag()`, so legacy language codes
are canonicalized (`iw` → `he`, `in` → `id`) and a script subtag such as `Hant`
survives to be matched.

Because resolution happens at render time, a re-render is all it takes to pick up
a new system language. On Android the generated receiver's intent-filter includes
`LOCALE_CHANGED`, so placed widgets re-render when the user switches language.
iOS has no equivalent hook: the new language shows up the next time WidgetKit
renders the widget.

## Reading translations back

`getData()` hands a localized field back as the same generated class, never as
a raw map and never null: whatever is stored is merged over the compiled
defaults locale by locale, so every locale always has text.

```dart
final data = await LocalizedGreetingHomeWidget.getData();
data.greeting.de;                 // the override if one was saved, else 'Hallo'
data.greeting.resolve('pt-PT');   // 'Olá' — falls onto the pt-BR sibling
```

The shipped values are also available on their own, without a read — one
`<key>Defaults` constant per keyed string:

```dart
LocalizedGreetingHomeWidget.greetingDefaults.en; // 'Hello'
```

`resolve(tag)` applies the widget's own matching for a single explicit tag —
useful for previews and tests, case-insensitively and with `_` treated as `-`.
On device the widget runs those same steps itself, across the user's whole
preferred-language list.

Because `getData` merges, it cannot tell a saved override apart from a shipped
default. If you need that distinction, read the preferences key yourself with
`HomeWidget.getWidgetData` — see [Access from native
code](#access-from-native-code) for the key and format.

## Mixing translated and fixed strings

Omit a key from `localization` to leave that string untranslated — a brand name,
for instance:

```dart
@HomeWidget(
  name: 'MyAppName',                            // omitted below → stays fixed
  description: 'Shows your recent activity',
  localization: HomeWidgetLocalization(
    defaultLocale: 'en',
    supportedLocales: ['en', 'de'],
    description: {'de': 'Zeigt deine letzten Aktivitäten'},
  ),
)
class Activity {}
```

A map that is *present* must cover every supported locale — a partial map is an
error rather than a silent gap. The gallery maps are the one exception: their
default-locale entry is optional, because the top-level `name` / `description`
can supply that text instead. If a string really is identical in some locale,
repeat it explicitly.

Note where the base text lives, since it differs by kind:

| | Base text | Map contains |
|---|---|---|
| `name` / `description` | `map[defaultLocale]` when present, otherwise the top-level annotation field | every other supported locale; the default locale optionally |
| `HWText.localized` / `HWString.localized` | — | **every** locale, including the default |

Supplying a gallery map with neither a default-locale entry nor the matching
top-level field is an error — there would be nothing to show outside the
translated locales. This bites `description` in particular, since the annotation
can leave it out entirely.

### Localized strings inside `HWJson`

An `HWJson` path may end on an `HWString.localized`. The JSON your app writes
stays the source of truth: whatever the path resolves to is rendered as-is.
Only when the path yields nothing — key missing, blob never written, value
unreadable — does the widget fall back to `defaultTranslations`, resolved
against the device locale like any other localized string.

```dart
HWText(
  HWJson(
    'profile',
    HWString.localized(
      'greeting',
      defaultTranslations: {'en': 'Hello', 'de': 'Hallo', 'pt-BR': 'Olá'},
    ),
  ),
)
```

The map is validated exactly like any other one: complete, default locale
required, locales drawn from `supportedLocales`, no placeholders. It does not
reach the generated translations class, though — a JSON leaf is written as part
of your JSON blob, not through `saveData`.

## Locale tags

Use BCP-47 tags (`en`, `de`, `pt-BR`, `zh-Hant`) in the shape
`language[-Script][-REGION]`; other BCP-47 variants and extensions are
rejected. The generator converts them to each platform's convention — Android
resource directories are not BCP-47, so `pt-BR` becomes `values-pt-rBR`,
`zh-Hant` becomes `values-b+zh+Hant` and `es-419` becomes `values-b+es+419`.

In the generated Dart class, tags become camelCase identifiers: `pt-BR` → `ptBR`.
Reserved words are suffixed, so Icelandic (`is`) becomes `is_`.

## Where translations end up

| | Fixed (`HWText.localized`) | Runtime-overridable (`HWString.localized`) | Gallery name & description |
|---|---|---|---|
| **Android** | `res/values[-<qualifier>]/home_widget_<snake_widget>.xml` (`home_widget_<snake_widget>_t_<hash>`) | one SharedPreferences key holding the JSON blob | `res/values[-<qualifier>]/home_widget_<snake_widget>.xml` (`home_widget_<snake_widget>_label` / `_description`) |
| **iOS** | `Localizable.xcstrings` (`home_widget_<snake_widget>_t_<hash>`) | one UserDefaults key holding the same JSON blob | `Localizable.xcstrings` when translated, otherwise a plain string literal |

The iOS catalog is generated and wired into the Xcode project automatically,
and requires Xcode 15 or newer.

A localized JSON leaf stores nothing of its own: its text arrives inside the
JSON blob your app writes under the JSON root key, and only its fallback map is
compiled into the widget.

On Android each widget gets its own resource file, rewritten in full on every
run and deleted from any locale directory the widget no longer ships text for;
your app's `strings.xml` is never read or written. Your own translations
therefore stay exactly where you put them.

Resource names for fixed strings hash the translation content, so identical
maps collapse onto one resource and an edited translation gets a fresh name.
Since the generated file is rewritten whole, nothing you delete from the
annotation lingers behind — edit translations in the annotation, not in the
generated resource file.

## Access from native code

Each `HWString.localized` field is stored under one preferences key — not one
key per locale: `home_widget.<WidgetClassName>.<key>`, for example
`home_widget.LocalizedGreeting.greeting`. The value is a JSON object mapping
locale tag to text:

```json
{"en": "Hi there", "de": "Hallo du", "pt-BR": "Oi"}
```

If native code reads this key directly, a missing or unreadable value should
be treated as "no override," falling back to the widget's compiled
`defaultTranslations`.

## Limitations

**Plurals and placeholders are not supported.** Which plural form applies depends
on runtime data, so a fixed per-locale map cannot express it. The generator
rejects strings containing `{placeholder}` or `%s`-style markers. Format the
string in your app with your usual l10n tooling and push the result through a
plain `HWString`:

```dart
await GreetingHomeWidget.saveData(
  itemCount: AppLocalizations.of(context).itemCount(items.length),
);
```

The trade-off is that a plain `HWString` holds one already-translated string, so
it stays stale after a language change until your app next runs.

Numbers and dates are the exception, and should *not* be pre-formatted into a
string for that very reason: push the raw value through an `HWInt`, `HWDouble`
or `HWDateTime` and let the widget format it in the device's locale at render
time — see [Formatting](/generator/formatting).

**Translated text is longer.** German typically runs 30–40% longer than English,
and widgets are small. Check your layouts in the longest locale you ship.

**The gallery entry cannot be changed at runtime** on either platform. On Android
the launcher reads it from the compiled manifest, so nothing your app does can
affect it; it is not offered on iOS alone in order to keep behavior consistent.

**`getData()` cannot tell an override from a default.** It merges the stored
blob over the compiled translations, so the result is always a complete,
non-null generated class — but a locale you never saved is indistinguishable
from one you saved the shipped text to. Read the preferences key directly with
`HomeWidget.getWidgetData` if you need the raw stored value.
