flutter - 无上下文的颤振本地化
问题描述
我正在尝试将我的应用程序本地化。我为支持的语言创建了所需的 string.arb 文件。
为什么AppLocalizations.of(context)
需要上下文?
我只是想访问文件/语言环境文件/类中的命名字符串。在应用程序的某个时刻,我构建了一个 List 并稍后通过使用单独的类覆盖某些字段来填充它。
但是,此类没有上下文,但我想在其中使用本地化字符串。我可以编写一个方法来获取我输入的任何字符串的本地化吗?
解决方案
我们可以通过使用get_it轻松解决这个问题,我们可以在此设置后的任何地方使用该字符串。
将此安装到您的 vscode Flutter Intl VSCode 扩展
设置
pubspec.yaml
dependencies: flutter: sdk: flutter flutter_localizations: # Add this line sdk: flutter # Add this line intl: ^0.17.0 # Add this line get_it: ^7.2.0 # Add this line flutter: uses-material-design: true generate: true # Add this line flutter_intl: # Add this line enabled: true # Add this line class_name: I10n # Add this line main_locale: en # Add this line arb_dir: lib/core/localization/l10n # Add this line output_dir: lib/core/localization/generated # Add this line
设置
main.dart
import 'package:component_gallery/core/localization/generated/l10n.dart'; import 'package:component_gallery/locator.dart'; import 'package:component_gallery/ui/pages/home.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; void main() { setupLocator(); runApp(App()); } class App extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( localizationsDelegates: [ I10n.delegate, GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ], supportedLocales: I10n.delegate.supportedLocales, localeResolutionCallback: (deviceLocale, supportedLocales) { if (supportedLocales .map((e) => e.languageCode) .contains(deviceLocale?.languageCode)) { return deviceLocale; } else { return const Locale('en', ''); } }, home: HomePage(), ); } }
设置
locator.dart
import 'package:component_gallery/core/services/navigation_service.dart'; import 'package:get_it/get_it.dart'; GetIt locator = GetIt.instance; void setupLocator() { locator.registerLazySingleton(() => I10n()); }
在没有上下文的情况下将它与 Get_it 一起使用
final I10n _i10n = locator<I10n>(); class MessageComponent extends StatelessWidget { @override Widget build(BuildContext context) { return Text( _i10n.sample, textAlign: TextAlign.center, ); } }
推荐阅读
- java - 使用休眠的场景的实体类
- jquery - jquery 显示的表单输入未在提交时发布-codeigniter
- kubernetes - 非云环境下 kubernetes 的负载均衡
- visual-c++ - 无法使用 regsvr32 注册 NmsCmCommon.dll
- python - 将自定义层和 py_function 与 opencv 方法一起使用
- windows - Powershell Windows 用户变量 appdata
- django - django-auth-ldap 无法验证 ldap 用户
- java - 从 PEM 字符串在 Java 中创建 DSA PublicKey
- flutter - 错误:无法在 pubspec.yaml 中找到目录条目
- java - 如何在热源上使用 groupBy