Ale*_*din 85
首先,您应该了解系统设置和您的应用程序设置之间的区别:
import 'dart:io';
final String defaultLocale = Platform.localeName; // Returns locale string in the form 'en_US'
Run Code Online (Sandbox Code Playgroud)
import 'package:flutter/material.dart';
final List<Locale> systemLocales = WidgetsBinding.instance.window.locales; // Returns the list of locales that user defined in the system settings.
Run Code Online (Sandbox Code Playgroud)
或者
import 'dart:ui';
final List<Locale> systemLocales = window.locales;
Run Code Online (Sandbox Code Playgroud)
MaterialApp 小部件支持本地化。它接受您决定应用程序支持的语言环境列表。这意味着您应该在supportedLocales属性的小部件初始化中明确定义它们,并提供所谓的“本地化委托”,它将实际转换为选定的语言环境(localizationsDelegates属性)。如果您的应用支持除en_US. 当您请求应用程序区域设置时,您将从supportedLocales.
final Locale appLocale = Localizations.localeOf(context);
Run Code Online (Sandbox Code Playgroud)
这仅在MaterialApp小部件已经初始化时才有效。您不能在MaterialApp初始化之前使用它。显然,如果您的应用小部件未初始化,则无法获取其语言环境。要使用它,您必须在子组件的build方法中调用此表达式。例如:
import 'dart:io';
final String defaultLocale = Platform.localeName; // Returns locale string in the form 'en_US'
Run Code Online (Sandbox Code Playgroud)
这将en_US在屏幕上打印文本(因为这是默认语言环境,我们没有提供任何其他内容)。系统区域设置是什么并不重要,因为在此示例中我们没有为我们的应用程序明确定义任何区域设置,因此它返回默认设置。
为了能够对系统区域设置更改做出反应,您应该使用一个实现WidgetsBindingObservermixin的有状态小部件并定义didChangeLocales将在系统区域设置更改时调用的方法:
import 'package:flutter/material.dart';
final List<Locale> systemLocales = WidgetsBinding.instance.window.locales; // Returns the list of locales that user defined in the system settings.
Run Code Online (Sandbox Code Playgroud)
总结以上所有内容,以下是在启动时获取语言环境并对系统设置更改做出反应的可视化示例:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Get the initial locale values
final String defaultSystemLocale = Platform.localeName;
final List<Locale> systemLocales = WidgetsBinding.instance.window.locales;
// Define locales that our app supports (no country codes, see comments below)
final appSupportedLocales = <Locale>[
Locale('ru'),
Locale('en'),
];
final MyApp myApp = MyApp(defaultSystemLocale, systemLocales);
runApp(
MaterialApp(
title: 'MyApp',
home: myApp,
supportedLocales: appSupportedLocales,
localizationsDelegates: [
// These are default localization delegates that implement the very basic translations for standard controls and date/time formats.
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
)
);
}
class MyApp extends StatefulWidget {
// Store initial locale settings here, they are unchanged
final String initialDefaultSystemLocale;
final List<Locale> initialSystemLocales;
MyApp(this.initialDefaultSystemLocale, this.initialSystemLocales);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
// Store dynamic changeable locale settings here, they change with the system changes
String currentDefaultSystemLocale;
List<Locale> currentSystemLocales;
// Here we read the current locale values
void setCurrentValues() {
currentSystemLocales = WidgetsBinding.instance.window.locales;
currentDefaultSystemLocale = Platform.localeName;
}
@override
void initState() {
// This is run when the widget is first time initialized
WidgetsBinding.instance.addObserver(this); // Subscribe to changes
setCurrentValues();
super.initState();
}
@override
void didChangeLocales(List<Locale> locale) {
// This is run when system locales are changed
super.didChangeLocales(locale);
// Update state with the new values and redraw controls
setState(() {
setCurrentValues();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text('Initial system default locale: ${widget.initialDefaultSystemLocale}.'),
Text('Initial language code: ${widget.initialDefaultSystemLocale.split('_')[0]}, country code: ${widget.initialDefaultSystemLocale.split('_')[1]}.'),
Text('Initial system locales:'),
for (var locale in widget.initialSystemLocales) Text(locale.toString()),
Text(''),
Text('Current system default locale: ${currentDefaultSystemLocale}.'),
Text('Current system locales:'),
for (var locale in currentSystemLocales) Text(locale.toString()),
Text(''),
Text('Selected application locale: ${Localizations.localeOf(context).toString()}.'),
Text(''),
Text('Current date: ${Localizations.of<MaterialLocalizations>(context, MaterialLocalizations).formatFullDate(DateTime.now())}.'),
Text('Current time zone: ${DateTime.now().timeZoneName} (offset ${DateTime.now().timeZoneOffset}).'),
],
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
支持的区域设置没有定义国家/地区代码,以向您展示当前应用区域设置的选择是如何工作的。在内部,MaterialApp小部件将应用程序支持的区域设置列表与系统传递的用户首选项列表进行比较,并选择最合适的区域设置。
假设我们有以下系统区域设置列表(en_US、en_GB、ru_RU):
** 点击缩略图查看完整截图。
我们的应用程序在启动时看起来像这样:
我们看到初始值和当前值显然相同。该应用程序选择了en语言环境作为其当前语言环境。
现在让我们将区域设置列表更改为以下内容,将 en_GB 区域设置移至顶部,使其成为默认系统区域设置:
该应用程序将反映此更改:
应用程序显然仍然选择en语言环境作为其当前语言环境,因为它与en_US和en_GB语言环境最接近。
现在让我们将设置更改为俄语作为默认系统值:
我们的应用程序将反映这一变化:
现在您可以看到ru区域设置被选为应用区域设置。
希望这有助于理解本地化在 Flutter 中是如何工作的,如何获取当前值,以及如何反映系统变化。关于语言环境委托的细节没有解释,因为它在这里是题外话。
PS:此代码仅在Android下测试。我认为只要稍加改动,它就可以适应所有其他平台。
Gün*_*uer 25
https://flutter.io/tutorials/internationalization/#tracking-locale
Locale myLocale = Localizations.localeOf(context);
提供countryCode和languageCode
https://docs.flutter.io/flutter/dart-ui/Locale-class.html
时区应该可用(未尝试)
DateTime.now().timeZoneName
Run Code Online (Sandbox Code Playgroud)
https://docs.flutter.io/flutter/dart-core/DateTime-class.html
小智 23
如果您编写 Platform.localeName,它会为您提供语言和国家/地区,例如“en_US”、“tr_TR”。
要仅获取“en”或“tr”,您可以使用 substring() 并获取前 2 个字母。
String deviceLanguage= Platform.localeName.substring(0,2);
Run Code Online (Sandbox Code Playgroud)
它只给你“en”或“tr”等......
如果您需要国家/地区代码,请使用此代码;
String deviceCountry= Platform.localeName.substring(3,5);
Run Code Online (Sandbox Code Playgroud)
它只给你“US”或“TR”等......
Cen*_*MUR 16
您可以使用
import 'dart:io' show Platform;
String languageCode = Platform.localeName.split('_')[0];
String countryCode = Platform.localeName.split('_')[1];
Run Code Online (Sandbox Code Playgroud)
小智 9
尝试这个:
import 'dart:ui' as ui;
......
@override
Widget build(BuildContext context) {
// get system language code
_sysLng = ui.window.locale.languageCode;
...
Run Code Online (Sandbox Code Playgroud)
使其发挥作用的步骤是:
将包作为依赖项添加到 pubspec.yaml 文件中
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
Run Code Online (Sandbox Code Playgroud)
导入flutter_localizations库并为MaterialApp指定localizationsDelegates和supportedLocales
import 'package:flutter_localizations/flutter_localizations.dart';
MaterialApp(
localizationsDelegates: [
// ... app-specific localization delegate[s] here
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: [
const Locale('en', ''), // English, no country code
const Locale('es', ''), // Spanish, no country code
// ... other locales the app supports
],
// ...
)
Run Code Online (Sandbox Code Playgroud)
仅适用于 iOS:打开 ios 模块并在本地化下添加支持的语言
获取当前区域设置
Locale myLocale = Localizations.localeOf(context);
如果需要,您可以访问区域设置的
CountryCode和languageCode字符串属性
| 归档时间: |
|
| 查看次数: |
12191 次 |
| 最近记录: |