You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中ChildScreen调用AppLocalization.of(context)始终返回null

问题原因及解决方法

核心问题

你的代码里MaterialApp未配置本地化相关的必要参数,导致AppLocalizations.of(context)无法获取到实例,返回null。

解决步骤

  1. 在MaterialApp中添加localizationsDelegates和supportedLocales参数,这两个是Flutter加载本地化资源的关键配置:

    • localizationsDelegates:指定提供本地化字符串的委托,直接使用AppLocalizations的静态属性即可
    • supportedLocales:声明应用支持的语言列表
  2. 修改后的完整代码:

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

void main() => runApp(const ParentScreen());

class ParentScreen extends StatelessWidget {
  const ParentScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // 添加本地化配置
      localizationsDelegates: AppLocalizations.localizationsDelegates,
      supportedLocales: AppLocalizations.supportedLocales,
      home: const Scaffold(
        body: ChildScreen(),
      ),
    );
  }
}

class ChildScreen extends StatelessWidget {
  const ChildScreen({super.key});

  @override
  Widget build(BuildContext context) {
    print('context = $context');
    // 现在可正常获取AppLocalizations实例
    return Text(AppLocalizations.of(context)!.appName);
  }
}

补充说明

  • 若你之前在ParentScreen中能正常调用AppLocalizations.of(context),说明它的context处于MaterialApp的子层级中(比如ParentScreen是MaterialApp的home或子组件),而非像当前代码这样作为返回MaterialApp的组件——返回MaterialApp的组件的context不属于MaterialApp层级,同样无法获取本地化实例。
  • 确保你已在pubspec.yaml中正确配置flutter_gen的本地化生成,示例配置:
flutter:
  generate: true
  localizations:
    sdk: flutter

内容的提问来源于stack exchange,提问作者i_am_somebody

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 01:54:57