AppLocalization.of(上下文) 的 Flutter returns null

Flutter returns null for AppLocalization.of(context)

我正在使用 Flutter 构建一个 Web-App 并且我想在我的新应用程序中使用 flutter 的国际化功能。我正在关注 Flutter-Tutorial,并尝试使用 arb-file 设置 app-title。如教程中所述,app_localization.dart-files 是为 'en' 和 'de' 正确创建的。然而,我在下面的代码中得到了一个空指针异常。

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)
      ),
    );
  }
}

事实上,AppLocalizations.of(context) returns null.

您应该在 MaterialApp 中添加 AppLocalizations

MaterialApp(
...
      localizationsDelegates: const [
        AppLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
      ],
      supportedLocales: AppLocalizations.supportedLocales,
...

这对我很有帮助。我在 MaterielApp 之上有一个 CupertinoApp,它覆盖了 MaterielApp 并且我的 AppLocalization.of(content) 为 null

https://github.com/flutter/flutter/issues/26365#issuecomment-523536339