问题
我正在使用AppLocalizations.of(context).myString
我的 null 安全颤振应用程序中的字符串国际化。
我的 IDE 告诉我AppLocalizations.of(context)
可以返回 null。处理这个问题的最佳方法是什么?有没有办法确保AppLocalizations.of(context)
永远不会返回 null?
目前,我正在采用以下方法:
AppLocalizations.of(context)?.myString ?? 'Fallback string'
完整的项目代码
发布规范.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!"
}
主要.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!'
),
);
}
}