auto_localize_cli 1.0.7
auto_localize_cli: ^1.0.7 copied to clipboard
AST-powered Flutter CLI that extracts hardcoded strings into .arb files, removes ancestor consts, and rewrites code to use context-less l10n getters.
auto_localize_cli #
⚡ Zero-config AST-powered Flutter CLI that automatically extracts hardcoded strings into .arb files, removes ancestor const modifiers, and rewrites source code to use a context-less, compile-safe l10n getter.
🎯 Why auto_localize_cli? #
Localizing a Flutter application is traditionally a slow, error-prone manual process:
- Scanning tens or hundreds of files to hunt down hardcoded string literals.
- Manually inventing unique
camelCasekeys and copying them into.arbfiles. - Breaking parent
consttrees across your widget tree and fixing resulting compile errors. - Passing
BuildContextdeep into controllers, repositories, and BLoCs just to access localized error messages.
auto_localize_cli automates this entire lifecycle via the Dart Analyzer AST:
- Extracts hardcoded UI strings and interpolations into your template
.arbfile. - Generates clean, semantic, collision-free
camelCasekeys automatically. - Automatically removes enclosing
consttokens up the widget tree so your code compiles immediately. - Rewrites widgets to use a clean, context-less global getter:
l10n.<key>. - Preserves 100% of your existing translations, comments, and project structure non-destructively.
- Adds 0 KB to your release bundle (pure
dev_dependenciestool).
⚡ Quick Start (4 Simple Steps) #
Step 1: Install #
Add auto_localize_cli to your project's dev_dependencies:
flutter pub add dev:auto_localize_cli
Or activate globally to use the CLI from anywhere:
dart pub global activate auto_localize_cli
Step 2: Initialize #
Scaffold your localization architecture with one command:
dart run auto_localize_cli init
# Or if globally activated:
auto_localize_cli init
(Optional: specify a custom base language: -l es, -l ru, -l bn)
What init sets up:
- Configures
pubspec.yamlwithflutter_localizations,intl, andflutter: generate: true. - Generates standard
l10n.yamlsettings. - Creates
lib/l10n/app_en.arbtemplate. - Scaffolds
lib/core/localization/localization_helper.dart(providingglobalNavigatorKey, context-lessl10n, and reactivechangeAppLocale). - Scaffolds
lib/core/localization/app_strings.dartfor non-UI error messages and business strings.
Step 3: Connect MaterialApp (One-Time Setup) #
In your lib/main.dart, wrap with ValueListenableBuilder<Locale?> and pass globalNavigatorKey:
import 'package:flutter/material.dart';
import 'package:your_app/core/localization/localization_helper.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<Locale?>(
valueListenable: localeNotifier, // Enables live runtime language switching
builder: (context, currentLocale, _) {
return MaterialApp(
navigatorKey: globalNavigatorKey, // <-- Enables context-less l10n everywhere!
locale: currentLocale,
title: l10n.appTitle, // Safe pre-mount fallback!
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: const HomeScreen(),
);
},
);
}
}
Step 4: Extract All Hardcoded Strings #
Write your Flutter widgets naturally with plain strings. When ready, run:
dart run auto_localize_cli extract
# Or if globally activated:
auto_localize_cli extract
Before & After Transformation:
Before:
class WelcomeBanner extends StatelessWidget {
const WelcomeBanner({super.key});
@override
Widget build(BuildContext context) {
return const Column(
children: [
Text('Welcome Back!'),
Text('Manage your account settings'),
],
);
}
}
After Running extract:
import 'package:your_app/core/localization/localization_helper.dart';
class WelcomeBanner extends StatelessWidget {
const WelcomeBanner({super.key});
@override
Widget build(BuildContext context) {
return Column( // <-- const automatically removed from parent!
children: [
Text(l10n.welcomeBack),
Text(l10n.manageYourAccountSettings),
],
);
}
}
Generated lib/l10n/app_en.arb:
{
"@@locale": "en",
"welcomeBack": "Welcome Back!",
"manageYourAccountSettings": "Manage your account settings"
}
Step 5: Add Other Languages in 2 Minutes (AI Workflow) #
- Copy
lib/l10n/app_en.arbinto ChatGPT, Claude, or Gemini:"Translate this Flutter .arb file into Spanish (
es). Keep all keys and{placeholder}tokens intact." - Save the output as
lib/l10n/app_es.arb. - Run
flutter gen-l10n. - Switch language live anywhere in your app:
changeAppLocale(const Locale('es'));
🛠️ CLI Command Reference #
1. init #
Initializes localization dependencies, templates, and helpers. Non-destructive; never overwrites existing .arb files or custom configs.
dart run auto_localize_cli init [options]
# or: auto_localize_cli init [options]
| Option | Shorthand | Default | Description |
|---|---|---|---|
--locale |
-l |
'en' |
Base locale code (e.g. en, es, bn, fr, de). |
--help |
-h |
Show command help. |
2. extract #
Scans Dart files, extracts strings to .arb, strips ancestor const, and rewrites source files.
dart run auto_localize_cli extract [options]
# or: auto_localize_cli extract [options]
| Option | Shorthand | Default | Description |
|---|---|---|---|
--git-diff |
-g |
false |
Sub-second $O(k)$ extraction. Scans only Git-modified and untracked files under lib/. Perfect for everyday coding and Git hooks. |
--file |
-f |
null |
Target a single Dart file (e.g. -f lib/features/home/home_screen.dart). |
--dry-run |
-d |
false |
Preview extracted strings and modified files without writing changes to disk or ARB. |
--no-cache |
false |
Force full re-scan, bypassing incremental sharded cache. | |
--workers |
-w |
CPU cores (max 8) | Number of parallel worker isolates for AST parsing. |
--locale |
-l |
Auto-detected | Specific target ARB file to extract into. Defaults to template in l10n.yaml. |
--help |
-h |
Show command help. |
🧩 Advanced Features & Architecture #
1. Context-Less l10n Anywhere #
Because l10n is backed by globalNavigatorKey, you can access localized strings from non-UI layers without passing BuildContext:
// Inside a BLoC, Cubit, or Repository:
import 'package:your_app/core/localization/localization_helper.dart';
class AuthRepository {
Future<void> login(String email, String password) async {
try {
await api.login(email, password);
} catch (e) {
throw Exception(l10n.invalidCredentialsError);
}
}
}
2. Pre-Mount Safe Fallback #
When initializing MaterialApp(title: l10n.appTitle), the title property is evaluated before NavigatorState is mounted. Instead of crashing, l10n safely falls back to lookupAppLocalizations(targetLocale) with multi-stage language and script matching (e.g. zh_Hant vs zh_Hans).
3. Existing rootNavigatorKey or GoRouter Support #
If your app already has an existing navigation key (e.g. with GoRouter or custom routing), simply register it:
// Option A: In main()
void main() {
setGlobalNavigatorKey(yourExistingRouterKey);
runApp(const MyApp());
}
// Option B: Pass globalNavigatorKey directly to GoRouter
final goRouter = GoRouter(
navigatorKey: globalNavigatorKey,
routes: [...],
);
4. String Interpolation & ICU Placeholders #
Strings containing $variables or ${expressions} are automatically converted to parameterized ICU messages:
Source Widget:
Text('Welcome back $name, you have ${items.length} unread messages')
Generated Code:
Text(l10n.welcomeBackNameUnreadMessages(name, items.length))
Generated ARB:
{
"welcomeBackNameUnreadMessages": "Welcome back {name}, you have {itemsLength} unread messages",
"@welcomeBackNameUnreadMessages": {
"placeholders": {
"name": {},
"itemsLength": {}
}
}
}
5. Smart Non-UI Class & Parameter Filtering #
The CLI extracts from:
- Positional argument of:
Text,SelectableText,Tooltip,showToast,showSnackBar,showDialog,showAlert. - 21 named UI parameters:
labelText,hintText,helperText,errorText,prefixText,suffixText,counterText,tooltip,semanticsLabel,title,subtitle,message,text,label,header,content,confirmText,cancelText,buttonText,action,prompt. - String getters and fields inside
lib/core/localization/app_strings.dart.
Strictly Ignored:
- Non-UI classes:
Exception,FormatException,Color,Uri,DateTime,File,Directory,Platform,Process,HttpClient,Logger, andprint(...). - Asset paths (
assets/...), URLs (https://...), route names (/home), emails, pure numbers ("2026","100%"), and default parameter values.
💡 Best Practices: BLoC, Cubit & State Management #
In Dart, an instance field initializer such as final String title = l10n.welcome; evaluates only once at instantiation time. If the user later changes the locale via changeAppLocale(...), an existing state object retains its old string.
Recommended Patterns:
// ✅ In UI: Evaluate dynamically in build()
Text(l10n.submitButton)
// ✅ In BLoC / Cubit State: Use a dynamic getter
class AuthSuccessState {
String get message => l10n.loginSuccess;
}
// ✅ Or emit key/enum in state and resolve in widget:
Text(state.isError ? l10n.genericError : l10n.successMessage)
📁 Recommended Folder Structure #
my_flutter_app/
├── pubspec.yaml
├── l10n.yaml # [Configurable: supports custom arb-dir]
├── lib/
│ ├── core/
│ │ └── localization/ # [Dedicated subfolder - never clashes with other core files]
│ │ ├── localization_helper.dart
│ │ └── app_strings.dart
│ ├── l10n/
│ │ ├── app_en.arb
│ │ └── app_es.arb
│ └── main.dart
📦 Zero Runtime Overhead #
auto_localize_cli is strictly a development and build-time compiler tool. It operates directly on your source code AST during development and adds 0 KB to your final release APK, AAB, or IPA bundle size!
🤝 Contributing & Issues #
Contributions, bug reports, and feature requests are welcome!
Feel free to open an issue or pull request on GitHub.
📄 License #
MIT License. Copyright (c) 2026 Dilip Sarkar.