
Hướng dẫn đầy đủ về bản địa hóa Flutter
Từ tệp ARB đến hỗ trợ RTL: bản địa hóa ứng dụng Flutter bằng easy_localization, xử lý số nhiều cho mọi ngôn ngữ và tự động dịch bằng AI.
Cài đặt easy_localization
Thêm gói easy_localization vào pubspec.yaml. Đây là gói Flutter i18n phổ biến nhất, hỗ trợ tệp ARB/JSON, số nhiều và phần mở rộng ngữ cảnh. Đồng thời thêm flutter_localizations từ SDK để định dạng ngày, số và hướng văn bản theo ngôn ngữ.
dependencies:
easy_localization: ^3.0.7
flutter_localizations:
sdk: flutterTạo tệp bản dịch ARB
Tệp Application Resource Bundle (ARB) là định dạng bản địa hóa tiêu chuẩn cho Flutter. Mỗi tệp chứa các cặp khóa-giá trị cùng siêu dữ liệu tùy chọn mô tả placeholder, quy tắc số nhiều và ngữ cảnh cho người dịch. Tạo một tệp cho mỗi ngôn ngữ trong thư mục assets/translations.
{
"@@locale": "en",
"appTitle": "My App",
"@appTitle": {
"description": "The title of the application"
},
"greeting": "Hello, {name}!",
"@greeting": {
"description": "Greeting with user name",
"placeholders": {
"name": {
"type": "String",
"example": "Alice"
}
}
},
"itemCount": "{count, plural, =0{No items} =1{1 item} other{{count} items}}",
"@itemCount": {
"description": "Number of items in the cart",
"placeholders": {
"count": {
"type": "num",
"format": "compact"
}
}
}
}Cấu hình ứng dụng
Bọc ứng dụng bằng widget EasyLocalization. Widget này quản lý trạng thái ngôn ngữ, tải bản dịch từ các tệp tài nguyên và cung cấp các delegate ngôn ngữ mà MaterialApp cần. Ba thuộc tính delegate bắt buộc là localizationsDelegates, supportedLocales và locale — tất cả đều có sẵn qua phần mở rộng ngữ cảnh.
import 'package:flutter/material.dart';
import 'package:easy_localization/easy_localization.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await EasyLocalization.ensureInitialized();
runApp(
EasyLocalization(
supportedLocales: [
Locale('en'),
Locale('ar'),
Locale('ja'),
Locale('de'),
],
path: 'assets/translations', // Path to your ARB/JSON files
fallbackLocale: Locale('en'),
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: context.localizationDelegates,
supportedLocales: context.supportedLocales,
locale: context.locale,
home: HomePage(),
);
}
}Dịch widget
Dùng phương thức mở rộng .tr() trên khóa chuỗi để lấy văn bản đã dịch trong bất kỳ widget nào. Với số nhiều, dùng .plural() kèm giá trị đếm. easy_localization cung cấp cả cú pháp phần mở rộng chuỗi ('key'.tr()) và cú pháp phương thức ngữ cảnh (context.tr('key')).
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('appTitle'.tr()), // Simple key
),
body: Column(
children: [
// String with variable interpolation
Text('greeting'.tr(args: ['Alice'])),
// Named arguments
Text('greeting'.tr(namedArgs: {'name': 'Alice'})),
// Plural form
Text('itemCount'.plural(3)),
],
),
);
}
}Xử lý số nhiều và biến
Flutter dùng ICU MessageFormat cho số nhiều — cùng tiêu chuẩn mà iOS, Android và web sử dụng. Xác định các dạng số nhiều bằng cú pháp {count, plural, ...} trong tệp ARB. Mỗi ngôn ngữ cần tập hợp dạng riêng dựa trên quy tắc số nhiều CLDR. Tiếng Ả Rập có 6 dạng, tiếng Nga có 4 dạng và tiếng Nhật có 1 dạng.
// English: 3 useful forms (=0, =1, other)
"itemCount": "{count, plural, =0{No items} =1{1 item} other{{count} items}}"
// Arabic: 6 forms (=0, =1, =2, few, many, other)
"itemCount": "{count, plural, =0{لا عناصر} =1{عنصر واحد} =2{عنصران} few{{count} عناصر} many{{count} عنصرًا} other{{count} عنصر}}"
// Japanese: 1 form (other)
"itemCount": "{count, plural, other{{count}個のアイテム}}"
// German: 2 forms (=1, other)
"itemCount": "{count, plural, =1{1 Artikel} other{{count} Artikel}}"
// Russian: 3 forms (one, few, many)
"itemCount": "{count, plural, =0{Нет товаров} one{{count} товар} few{{count} товара} many{{count} товаров} other{{count} товаров}}"// Simple variable
"welcome": "Welcome, {name}!"
// Multiple variables
"orderStatus": "Order #{orderId} — {status}"
// Variable in plural context
"unreadMessages": "{count, plural, =0{No unread messages} =1{1 unread message from {sender}} other{{count} unread messages}}"
// In widgets:
Text('welcome'.tr(namedArgs: {'name': userName}));
Text('orderStatus'.tr(namedArgs: {'orderId': '1234', 'status': 'Shipped'}));
Text('unreadMessages'.plural(count, namedArgs: {'sender': senderName}));Hỗ trợ ngôn ngữ RTL
Flutter tự động lật toàn bộ bố cục khi ngôn ngữ viết từ phải sang trái (tiếng Ả Rập, tiếng Do Thái, tiếng Ba Tư, tiếng Urdu). Tuy nhiên, mã của bạn phải dùng widget và thuộc tính nhận biết hướng để lật chính xác. Thay các giá trị trái/phải mã hóa cứng bằng giá trị bắt đầu/kết thúc tương ứng.
import 'package:flutter/material.dart';
class AdaptiveLayout extends StatelessWidget {
@override
Widget build(BuildContext context) {
final isRtl = Directionality.of(context) == TextDirection.rtl;
return Scaffold(
body: Row(
children: [
// Use start/end instead of left/right
Expanded(
child: Padding(
padding: EdgeInsetsDirectional.only(
start: 16.0, // Leading edge (left in LTR, right in RTL)
end: 8.0, // Trailing edge
),
child: Text('content'.tr()),
),
),
// Flip icons for RTL
Icon(
isRtl ? Icons.arrow_back : Icons.arrow_forward,
),
],
),
);
}
}// Use Directional widgets for RTL-aware layouts
EdgeInsetsDirectional.only(start: 16, end: 8) // Not EdgeInsets.only(left: 16, right: 8)
AlignmentDirectional.centerStart // Not Alignment.centerLeft
BorderRadiusDirectional.only(topStart: Radius.circular(8))
// Automatically mirrors when locale changes to Arabic, Hebrew, etc.
// No conditional logic needed — Flutter handles text direction from localeChuỗi dự phòng ngôn ngữ thông minh
Theo mặc định, khi thiếu bản dịch pt-BR, Flutter chuyển thẳng sang tiếng Anh — bỏ qua bản dịch pt-PT hoàn toàn phù hợp. Gói locale_chain khắc phục điều này bằng chuỗi dự phòng có thể cấu hình. Chỉ cần một dòng thiết lập, không cần di chuyển — các lệnh gọi .tr() hiện có vẫn hoạt động.
import 'package:locale_chain/locale_chain.dart';
import 'package:locale_chain/easy_localization.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await EasyLocalization.ensureInitialized();
LocaleChain.configure(); // Enable smart fallback chains
runApp(
EasyLocalization(
supportedLocales: [
Locale('en'),
Locale('pt', 'BR'),
Locale('pt', 'PT'),
Locale('es'),
Locale('es', 'MX'),
],
path: 'assets/translations',
assetLoader: LocaleChainAssetLoader( // Swap in the chain loader
baseLoader: RootBundleAssetLoader(),
),
fallbackLocale: Locale('en'),
child: MyApp(),
),
);
}
// Result: pt-BR user sees pt-PT translations when pt-BR keys are missing,
// instead of falling back directly to English.// Override specific chains while keeping built-in defaults
LocaleChain.configure(
fallbacks: {
'pt-BR': ['pt-PT', 'pt'], // pt-BR → pt-PT → pt → en
'es-MX': ['es-419', 'es'], // es-MX → es-419 → es → en
'fr-CA': ['fr'], // fr-CA → fr → en
},
);
// Or replace all defaults with your own chains
LocaleChain.configure(
fallbacks: {
'zh-Hant-HK': ['zh-Hant-TW', 'zh-Hans'],
'pt-BR': ['pt-PT', 'pt'],
},
mergeDefaults: false, // Only your chains, no built-in defaults
);Tự động hóa bản dịch
Sau khi hoàn tất thiết lập bản địa hóa, hãy dùng AI để dịch tệp ARB. Trong IDE, yêu cầu trợ lý AI dịch tệp ARB nguồn hoặc dùng i18n Agent CLI trong quy trình CI/CD. Siêu dữ liệu ARB (placeholder, mô tả) cung cấp ngữ cảnh giúp nâng cao chất lượng bản dịch.
# In your IDE, ask your AI assistant:
> Translate assets/translations/en.arb to Arabic, Japanese, and German
✓ ar.arb created (1.4s)
✓ ja.arb created (1.2s)
✓ de.arb created (1.1s)
# Or use the CLI in CI/CD:
npx i18n-agent translate assets/translations/en.arb --lang ar,ja,deTự động đảm bảo chất lượng bản dịch
Lỗi thường gặp
Không tìm thấy tệp bản dịch khi chạy
Cú pháp tệp ARB không hợp lệ
Thay đổi bản dịch không xuất hiện khi tải lại nóng
Giá trị trái/phải mã hóa cứng làm hỏng RTL
Cấu trúc tệp đề xuất
my_flutter_app/
├── assets/
│ └── translations/
│ ├── en.arb # Source language (English)
│ ├── ar.arb # Arabic (with 6 plural forms)
│ ├── de.arb # German
│ ├── ja.arb # Japanese
│ ├── pt-BR.arb # Brazilian Portuguese
│ └── pt-PT.arb # European Portuguese
├── lib/
│ ├── main.dart # App entry with EasyLocalization
│ ├── app.dart # MaterialApp with locale delegates
│ └── widgets/
│ └── language_switcher.dart
├── pubspec.yaml # Dependencies
└── analysis_options.yamlDùng thử i18n Agent ngay
Thả tệp bản dịch của bạn vào đây
JSON, YAML, PO, XML, CSV, Markdown, Properties
hoặc nhấp để duyệt
Ngôn ngữ đích
Dự phòng ngôn ngữ bằng locale_chain
Khi thiếu khóa bản dịch trong một ngôn ngữ vùng miền như pt-BR, Flutter chuyển thẳng sang ngôn ngữ mẫu thay vì kiểm tra ngôn ngữ cha pt trước.
flutter pub add locale_chainimport 'package:locale_chain/locale_chain.dart';
LocaleChain.configure(fallbacks: {
'pt-BR': ['pt', 'en'],
'zh-Hant-HK': ['zh-Hant', 'zh', 'en'],
});
LocaleChainAssetLoader(baseLoader: RootBundleAssetLoader());Xem Hướng dẫn về dự phòng ngôn ngữ để biết danh sách đầy đủ các framework được hỗ trợ và 75 chuỗi tích hợp sẵn. Learn more →