我正在尝试为我的应用程序实现国际化,但它不允许我使用我喜欢的语言(印度尼西亚语)。
从医生那里,它让我把localizationsDelegates
添加到我的MaterialApp
中。由于我使用的是GetX,这里的MaterialApp
被包装在GetMaterialApp
中。
但是当我这么做的时候,它给我一个错误:
Exception has occurred.
UnsupportedError (Unsupported operation: Cannot modify unmodifiable map)
我试图删除localizationsDelegates
,它抛出了另一个错误:
Exception has occurred.
FlutterError (No MaterialLocalizations found.
TabBar widgets require MaterialLocalizations to be provided by a Localizations widget ancestor.
The material library uses Localizations to generate messages, labels, and abbreviations.
To introduce a MaterialLocalizations, either use a MaterialApp at the root of your application to include them automatically, or add a Localization widget with a MaterialLocalizations delegate.
The specific widget that could not find a MaterialLocalizations ancestor was:
TabBar
但是,当我硬编码GetMaterialApp
的GetMaterialApp
属性到Locale('en', 'US')
并注释localizationsDelegates
__时,它就能工作了。
你们知道为什么怎么解决吗?
无论如何,这是我的main.dart
(和一些相关文件)的样子。
main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Get.putAsync(() => EnvService().init());
await Get.putAsync(() => IntlService().init());
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: "MyApp",
initialRoute: AppPages.INITIAL,
getPages: AppPages.routes,
themeMode: ThemeMode.dark,
theme: MyAppTheme.light,
darkTheme: MyAppTheme.dark,
debugShowCheckedModeBanner: false,
// translations: AppTranslations(),
locale: const Locale('en', 'US'),
fallbackLocale: const Locale('id', 'ID'),
supportedLocales: const [
Locale('en', 'US'),
Locale('id', 'ID'),
],
//
//
// UNCOMMENT THIS LINE, YOUR PHONE WILL EXPLODE!
// localizationsDelegates: GlobalMaterialLocalizations.delegates,
);
}
}
env_service.dart
class EnvService extends GetxService {
static EnvService get instance => Get.find();
Future<EnvService> init() async {
await dotenv.load();
return this;
}
Locale get defaultLocale {
final locale = dotenv.get('DEFAULT_LOCALE', fallback: 'id');
if (locale != 'id') {
return const Locale('en', 'US');
}
return Locale(locale, locale.toUpperCase());
}
}
intl_service.dart
class IntlService extends GetxService {
static IntlService get instance => Get.find();
Locale get _locale {
return Get.locale ?? EnvService.instance.defaultLocale;
}
Future<IntlService> init() async {
await initializeDateFormatting(_locale.countryCode);
return this;
}
String formatCurrency(double number) {
final formatter = NumberFormat.simpleCurrency(decimalDigits: 0);
return formatter.format(number);
}
String formatDate(DateTime? dateTime, [String? format]) {
if (dateTime == null) {
return '';
}
return DateFormat(format).format(dateTime);
}
}
发布于 2022-11-14 20:54:29
尝试在GetMaterialApp
中添加以下内容
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
https://stackoverflow.com/questions/74433986
复制相似问题