flutter插件 - fluintl(国际化)

简介

官方文档

fluintl 是一个为应用提供国际化的库,可快速集成实现应用多语言。
该库封装了一个国际化支持类,通过提供统一方法getString(id)获取字符串。CustomLocalizations多语言支持类。LBaseState可简洁获取字符串。

使用

  • 修改pubspec.yaml文件,添加依赖fluintl
# ... dev_dependencies: # ... fluintl: ^0.1.3 # ...
  • lib/目录下新建res/目录

  • lib/res/目录下新建strings.dart文件。创建多语言资源字符串id管理类Ids 和 多语言资源Map

// 多语言资源id管理类. class Ids { static String titleHome = 'title_home'; } // 简单多语言资源. Map<String, Map<String, String>> localizedSimpleValues = { 'en': { Ids.titleHome: 'Home', }, 'zh': { Ids.titleHome: '主页', }, }; // 多语言资源. Map<String, Map<String, Map<String, String>>> localizedValues = { 'en': { 'US': { Ids.titleHome: 'Home', } }, 'zh': { 'CN': { Ids.titleHome: '主页', }, 'HK': { Ids.titleHome: '主頁', }, } };
  • 修改lib/main.dart文件。在MyApp initState配置多语言资源(可配置通用或简单多语言资源,二选一);在MaterialApp指定localizationsDelegatessupportedLocales
import 'package:fluintl/fluintl.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import './res/strings.dart'; void main() { runApp(MyApp()); } class MyApp extends StatefulWidget { @override State<StatefulWidget> createState() { return MyAppState(); } } class MyAppState extends State<MyApp> { @override void initState() { super.initState(); // 配置简单多语言资源 // setLocalizedSimpleValues(localizedSimpleValues); // // 配置多语言资源 setLocalizedValues(localizedValues); } @override Widget build(BuildContext context) { return new MaterialApp( // ... locale: _locale, localizationsDelegates: [ GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, // 设置本地化代理 CustomLocalizations.delegate ], // 设置支持本地化语言集合 supportedLocales: CustomLocalizations.supportedLocales, ); } }
  • 在代码中使用
import 'package:fluintl/fluintl.dart'; IntlUtil.getString(context, Ids.titleHome); IntlUtil.getString(context, Ids.titleHome, params: [param1, param2]);  CustomLocalizations.of(context).getString(Ids.titleHome) // 比如在widget中 Text( IntlUtil.getString(context, Ids.titleHome), style: TextStyle(fontSize: 13.0) )

fluro也支持复用
替换字符串格式要求:'%${index}$s'{index} 第几个参数,从0开始。

Ids.click_times: '%\$0\$s点击了%\$1\$s次', IntlUtil.getString(context, Ids.click_times, params: ['Tom', '$_counter']) // print: Tom点击了0次

创作不易,若本文对你有帮助,欢迎打赏支持作者!

 分享给好友: