Why Flutter returns null for AppLocalizations.of(context)? 

If you're trying to access AppLocalizations.of(context) in your Flutter app and getting a null value, it's likely because your localization configuration is incorrect. This could be because you didn't register AppLocalizations.delegate in the localizationsDelegates of your MaterialApp widget or something similar.

Even if you've configured everything correctly, you might still get a null value when trying to access localization messages in the MaterialApp widget. This happens when the localization is not ready yet, which is often the case when trying to localize the title property. To fix this, you can use the onGenerateTitle property of the MaterialApp widget instead.

If you're defining a page widget directly within the MaterialApp widget and getting a null value when trying to access AppLocalizations.of(context), you can wrap your page widget with the Builder widget. This introduces an additional BuildContext element that allows you to access the localization messages. The Builder widget is an alternative to defining a StatelessWidget subclass and is a quick and easy solution that can solve the problem in most cases.

import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: AppLocalizations.localizationsDelegates,
      supportedLocales: AppLocalizations.supportedLocales,

      // title: AppLocalizations.of(context)!.appTitle,
      onGenerateTitle: (context) => AppLocalizations.of(context)!.appTitle,
      
      // home: Scaffold(
      //   appBar: AppBar(
      //     title: Text(AppLocalizations.of(context)!.pageHomeTitle),
      //   ),
      //   body: Column(
      //     children: <Widget>[
      //       Text(AppLocalizations.of(context)!.pageHomeWelcome)
      //     ],
      //   ),
      // ),
      home: Builder(
        builder: (context) => Scaffold(
          appBar: AppBar(
            title: Text(AppLocalizations.of(context)!.pageHomeTitle),
          ),
          body: Column(
            children: <Widget>[
              Text(AppLocalizations.of(context)!.pageHomeWelcome)
            ],
          ),
        ),
      ),
    );
  }
}

Flutter internationalization tutorial:

Copyrights 2024 © Localizely