【发布时间】:2021-04-15 20:09:27
【问题描述】:
问题
我正在使用 AppLocalizations.of(context).myString 在我的 null 安全颤振应用程序中国际化字符串。
我的 IDE 告诉我 AppLocalizations.of(context) 可以返回 null。处理这个问题的最佳方法是什么?有没有办法确保AppLocalizations.of(context) 永远不会返回 null?
目前,我采用以下方法:
AppLocalizations.of(context)?.myString ?? 'Fallback string'
完整的项目代码
Pubspec.yaml
name: Sample Intl Project
description: A sample project
publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ">=2.12.0-133.2.beta <3.0.0"
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
intl: ^0.17.0-nullsafety.2
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
generate: true
l10n.yaml
arb-dir: lib/l10n
template-arb-file: app_en_US.arb
output-localization-file: app_localizations.dart
l10n/app_en_US.arb
{
"helloWorld": "Hello World!",
"@helloWorld": {
"description": "Greeting"
}
l10n/app_en.arb
{
"helloWorld": "Hello World!"
}
main.dart
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
void main() {
runApp(App());
}
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Sample App',
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Home()
);
}
}
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Text(
AppLocalizations.of(context)?.helloWorld ?? 'Hello World!'
),
);
}
}
【问题讨论】:
-
AppLocalizations的包是从哪里来的? -
它是在你向 Flutter 应用添加国际化配置时自动生成的。请参阅docs,特别是第 6 步和第 7 步。
-
能否请您提供更多代码,我没有出现此消息
-
试试
AppLocalizations.of(context).myString。您需要首先通过执行以下命令来选择 null 安全性:flutter channel beta; flutter upgradein a terminal。
标签: flutter dart internationalization dart-null-safety