- 添加依赖
- 书写翻译包
- 在页面中使用
添加依赖
dependencies:
flutter:
sdk: flutter
i18n_extension: ^8.0.0
翻译包
大致结构如此,pt_br代表你将使用这种语言作为你的输入语言,
// lib/utils/i18n.dart
import 'package:i18n_extension/i18n_extension.dart';
extension Localization on String {
//pt_br代表你将使用这种语言作为你的输入语言
static final _t = Translations("pt_br") +
{
"en_us": "Hello %s, this is %s",
"pt_br": "Olá %s, aqui é %s",
"zh_cn": "哈喽 %s , 这是 %s"
} + {
"en_us": "Hi",
"pt_br": "Olá",
"zh_cn": "嗨"
};
String get i18n => localize(this, _t);
String fill(List<Object> params) => localizeFill(this, params);
}
在页面中使用
import 'package:i18n_extension/i18n_widget.dart';
import 'package:<projectName>/utils/i18n.dart';
//将它包裹在入口处
***
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return I18n(initialLocale:Locale("en","US"),
child:<U app main>;
}
}
***
一般开发我们用中文作为默认,调整翻译包默认语言即可
I18n(
initialLocale: const Locale("en","US"),
child: Text("嗨".i18n), //--> Hi
最后完成持久化
使用本地缓存当前选择的语言即可。