'Flutter returns null for AppLocalization.of(context)
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.
Solution 1:[1]
You should add the AppLocalizations
in your MaterialApp:
MaterialApp(
...
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
...
Solution 2:[2]
Thats helped me. I had a CupertinoApp above MaterielApp, this override the MaterielApp and my AppLocalization.of(content) was null
https://github.com/flutter/flutter/issues/26365#issuecomment-523536339
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | croxx5f |
Solution 2 | Aiiboo |