I am using Flutter to build a Web-App and I want to use the internationalization feature of flutter on my new app. I was following the Flutter-Tutorial and I try to set the app-title using the arb-file. As mentioned in the tutorial, the app_localization.dart-files are created properly for 'en' and 'de'. Yet, I get a null pointer exception in the following code.
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'MyApp',
localizationsDelegates: [
AppLocalizations.delegate, // Post-EDIT due to croxx5f
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: [
Locale('de', ''),
Locale('en', ''),
],
theme: ThemeData(
primarySwatch: Colors.red,
),
home: Scaffold(
appBar: AppBar(
title: Text(AppLocalizations.of(context)!.appTitle),
),
body: Text(AppLocalizations.of(context)!.appTitle)
),
);
}
}
In fact, AppLocalizations.of(context) returns null.
On my case, using the Scaffold()
as home:
of MaterialApp()
for testing purpose caused the issue.
Once I created a Separate HomePage()
widget and used that as
home: HomePage()
the problem is gone.
When I put the Scaffold(), as a direct child to MaterialApp, that treats as there were no parent contexts available with AppLocalizationDelegate, as the MaterialApp is the main context builder for all the underlying widgets.
Bad code:
return MaterialApp(
home: Scaffold(
body: Txt(text: AppLocalizations.of(context)?.helloWorld)
),
locale: Locale('ar'),
supportedLocales: [Locale('en'),Locale('ar')],
localizationsDelegates: [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
]);
},
));
Good code:
return MaterialApp(
home: HomePag(),
locale: Locale('ar'),
supportedLocales: [Locale('en'),Locale('ar')],
localizationsDelegates: [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
]);
},
));
class HomePag extends StatefulWidget {
const HomePag({Key? key}) : super(key: key);
@override
State<HomePag> createState() => _HomePagState();
}
class _HomePagState extends State<HomePag> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
children: [
Txt(text: AppLocalizations.of(context)?.helloWorld),
// Txt(text: AppLocalizations.of(context)?.translate('help'))
],
),
),
);
}
}
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