多语言基本实现
导入国际化插件:在根目录pubspec.yaml
导入
dependencies:flutter:sdk: flutterflutter_localizations:sdk: flutter
让app支持语言
runApp(MaterialApp(routes: {Routes.page2: (context) => const LocalizationPage1(),Routes.page1: (context) => const LocalizationPage(),},initialRoute: Routes.page1,localizationsDelegates: [//使material组件支持多语言GlobalMaterialLocalizations.delegate,//定义组件默认的文本方向,从左往右或者从右往左GlobalWidgetsLocalizations.delegate,//注册定义的中文语言包ZhCNLocaleDelegate()],//语种定义supportedLocales: LocalesCode.locales,//指定当前语言// locale: LocalesCode.initLocale,//语言切换回调返回系统语言列表localeListResolutionCallback:(List<Locale>? locales, Iterable<Locale> supportedLocales) {print('localeListResolutionCallback语言列表=$locales');return null;},// //语言切换回调返回系统单个语言localeResolutionCallback:(Locale? locale, Iterable<Locale> supportedLocales) {// print('localeResolutionCallback语言=$locale');return null;},));
class LocalizationPage extends StatefulWidget {const LocalizationPage({Key? key}) : super(key: key);@overrideState<StatefulWidget> createState() => LocalizationState();}class LocalizationState extends State<LocalizationPage> {@overrideWidget build(BuildContext context) => MaterialApp(home: Scaffold(body: Column(mainAxisAlignment: MainAxisAlignment.center,crossAxisAlignment: CrossAxisAlignment.center,children: [Text('当前语言' '${Localizations.localeOf(context)}'),MaterialButton(onPressed: () {Navigator.of(context).pushNamed(Routes.page2);},child: const Text('跳转'),)],),),);}class LocalizationPage1 extends StatelessWidget {const LocalizationPage1({Key? key}) : super(key: key);@overrideWidget build(BuildContext context) => Scaffold(body: Column(mainAxisAlignment: MainAxisAlignment.center,crossAxisAlignment: CrossAxisAlignment.center,children: [Text('页面2当前语言' '${ZhCNLocale.of(context)?.title}'),MaterialButton(onPressed: () {Navigator.of(context).pop();},child: const Text('关闭'),)],),);}
自定义语言包
////// 实现中文语言包/// class ZhCNLocale {final bool _isLocale;ZhCNLocale(this._isLocale);static ZhCNLocale? of(BuildContext context) {return Localizations.of<ZhCNLocale>(context, ZhCNLocale);}String get title {if (_isLocale) {return '中文标题';} else {return 'title';}}}////// 定义中文语言包class ZhCNLocaleDelegate extends LocalizationsDelegate<ZhCNLocale> {//是否支持当前语言@overridebool isSupported(Locale locale) {var codes = LocalesCode.locales.map((e) {return e.languageCode;});return codes.contains(locale.languageCode);}@overrideFuture<ZhCNLocale> load(Locale locale) {return SynchronousFuture<ZhCNLocale>(ZhCNLocale(locale.languageCode == LocalesCode.zh_cn.languageCode));}@overridebool shouldReload(covariant LocalizationsDelegate<ZhCNLocale> old) {return false;}}
这种方式实现起颇为繁琐