You need to enable JavaScript to run this app. Flutter Intl 官方组件用本地化文本报the getter was called on null求助
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Intl 官方组件用本地化文本报the getter was called on null求助

无自定义重写的修复方案

错误本质

你遇到的NoSuchMethodError: the getter 'value' was called on null和Flutter官方组件的静态逻辑、动态加载冲突完全无关,本质是调用S.of(context)时,当前使用的context路径上还未挂载有效的本地化实例,导致S.of()返回了null。
自定义组件和基础Text可以正常运行,是因为这些场景下你是在组件本身的build生命周期内取的本地化值,而官方组件报错的场景,基本都是你提前在非有效上下文时机取了值。

具体落地修复点

所有操作都不需要重写、封装任何官方组件:

  • 修正取值时机,把本地化取值动作从「组件构造阶段、initState、类静态/成员常量初始化」移动到对应组件build方法内部,使用build方法传入的有效context取值:
    错误写法参考:
    class _DemoPageState extends State<DemoPage> {
      // 错误:类成员变量初始化时调用S.of(context),此时组件还未挂载,context无效
      String fieldLabel = S.of(context).formFieldHint;
    
      @override
      Widget build(BuildContext context) {
        return TextFormField(
          decoration: InputDecoration(labelText: fieldLabel),
        );
      }
    }
    
    正确写法参考:
    class _DemoPageState extends State<DemoPage> {
      @override
      Widget build(BuildContext context) {
        // 在build方法内取值,此处context是被Localizations覆盖的有效上下文,不会返回null
        final fieldLabel = S.of(context).formFieldHint;
        return TextFormField(
          decoration: InputDecoration(labelText: fieldLabel),
          // ListTile、DropdownButton等组件的文本参数,同样直接在build内取值传入即可
          title: ListTile(
            title: Text(S.of(context).listTileMainTitle),
            subtitle: Text(S.of(context).listTileSubTitle),
          ),
          items: [
            DropdownMenuItem(
              value: 0,
              child: Text(S.of(context).dropdownFirstOption),
            ),
          ],
        );
      }
    }
    
  • 如果需要跨生命周期使用本地化文本,不要在成员变量里提前缓存,改用didChangeDependencies生命周期方法取值:

    这个方法的触发时机是Localizations完成加载、组件依赖更新之后,此时调用S.of(context)一定能拿到有效实例,不会返回null。

    String? cachedHintText;
    @override
    void didChangeDependencies() {
      super.didChangeDependencies();
      cachedHintText = S.of(context).searchHint;
    }
    
  • 针对DropdownButton、PopupMenuButton这类需要传入子组件列表的组件,不要把列表定义为类的静态常量/成员常量,一定要在build方法内根据当前上下文动态生成列表,避免列表初始化时context无效导致null值。
  • 检查本地化代理的配置顺序,确保把Intl生成的S.delegate放在localizationsDelegates列表的最前面,避免代理加载顺序错乱导致部分组件树内的context无法获取本地化实例:
    MaterialApp(
      localizationsDelegates: const [
        S.delegate, // 自定义Intl代理前置
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: S.delegate.supportedLocales,
    )
    

注意:以上所有调整完成后,不管是TextFormField、ListTile、DropdownButton还是其他任意Flutter官方组件,只要传入的本地化文本是在有效build上下文内取值生成的,就不会触发null报错,完全不需要为了适配i18n重写整套官方组件。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.23 12:24:01