900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > Flutter 国际化 多语言 语言切换 自定义语言包

Flutter 国际化 多语言 语言切换 自定义语言包

时间:2024-02-16 21:24:49

相关推荐

Flutter 国际化 多语言 语言切换 自定义语言包

多语言基本实现

导入国际化插件:在根目录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;}}

这种方式实现起颇为繁琐

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。