Flutter returns null for AppLocalization.of(context)
You should add the AppLocalizations
in your MaterialApp:
MaterialApp(
...
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
...
Searles
Software Architect for some years. I also worked in akademia on programming and programming languages. I have implemented an inversible parser (which is actually pretty cool) and created two nice fractal apps for Android: Fract and Fractview. Likes: Kotlin, A philosophy of software design, Music by Sigur Ros, Bicycling. Dislikes: Mean people.
Updated on December 30, 2022Comments
-
Searles over 1 year
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.
-
Searles over 2 yearsOk, apart from the missing AppLocalization.delegate, I noticed that I forgot to add 'intl: ^0.17.0 # Add this line'. Still after that I got the NPE, yet after fixing the title to a constant string, it vanished. Thanks!
-
Lennert about 2 yearsCould you post your working code as an answer to this question, please. The accepted answer does not resolve the problem, but you seem to have solved it.
-
-
Searles over 2 yearsUnfortunately that did not change much, I still get the NPE...
-
croxx5f over 2 yearsTry to run
flutter clean && flutter pub get dependencies && flutter packages get
to trigger the codegen from the .arb