Skip to content

Getting Started

Kenny Mochizuki Escalona edited this page Aug 16, 2026 · 1 revision

Getting Started

Installation

Add layrz_i18n to your pubspec.yaml:

dependencies:
  layrz_i18n: ^1.0.0

Then run flutter pub get.

Defining Languages

Create a list of available languages with their translations:

final languages = [
  AvailableLanguage(
    id: '1',
    name: 'English',
    code: 'en',
    fallback: 'en',
    messages: {
      'greeting': 'Hello, {name}!',
      'items': 'One item | {count} items',
      'welcome': 'Welcome to [link]',
    },
  ),
  AvailableLanguage(
    id: '2',
    name: 'Español',
    code: 'es',
    fallback: 'en',
    messages: {
      'greeting': '¡Hola, {name}!',
      'items': 'Un elemento | {count} elementos',
      'welcome': 'Bienvenido a [link]',
    },
  ),
];

final supportedLocales = languages.map((l) => l.getLocale()).toList();

Wiring into WidgetsApp

LayrzI18n works with a bare WidgetsApp. Note that WidgetsApp does not provide default values for color: (required) or text direction, so use the builder: parameter with Directionality:

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return WidgetsApp(
      color: const Color(0xFF000000),
      locale: LayrzI18n.getClosestLocale(
        supportedLocales: supportedLocales,
        fallbackLocale: const Locale('en'),
      ),
      localizationsDelegates: [
        LayrzI18n.delegate(
          languages: languages,
          supportedLocales: supportedLocales,
          fallbackLocale: const Locale('en'),
        ),
      ],
      supportedLocales: supportedLocales,
      builder: (BuildContext context, Widget? child) {
        return Directionality(
          textDirection: TextDirection.ltr,
          child: const HomePage(),
        );
      },
    );
  }
}

Reading Translations

Use context.i18n to access translations in your widgets:

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(context.i18n.t('greeting', {'name': 'Alice'})),
        Text(context.i18n.tc('items', 5, {'count': '5'})),
        RichText(text: context.i18n.te('welcome', richArgs: {'link': TextSpan(text: 'our site')})),
      ],
    );
  }
}

Alternatively, use LayrzI18n.of(context) for the explicit form:

final i18n = LayrzI18n.of(context);
Text(i18n.t('greeting', {'name': 'Alice'}))

Clone this wiki locally