I am using AppLocalizations.of(context).myString
to internationalize strings in my null safe flutter app.
My IDE tells me that AppLocalizations.of(context)
can return null. What's the best approach to handle this? Is there a way to ensure AppLocalizations.of(context)
never returns null?
Currently, I am resorting to the following approach:
AppLocalizations.of(context)?.myString ?? 'Fallback string'
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
arb-dir: lib/l10n
template-arb-file: app_en_US.arb
output-localization-file: app_localizations.dart
{
"helloWorld": "Hello World!",
"@helloWorld": {
"description": "Greeting"
}
{
"helloWorld": "Hello World!"
}
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!'
),
);
}
}
add this line in l10n.yaml:
nullable-getter: false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With