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

如何在Flutter的Stateful Widget中正确使用ARB文件实现本地化功能

问题根源

你代码里的3个核心问题导致本地化返回null:

  • 注释掉了supportedLocales参数,Flutter无法匹配当前Locale和你支持的语言列表,无法加载对应ARB资源
  • State类继承错误,_AnotherPageState应该继承State<AnotherPage>,你写的AnothertState是不存在的错误类,会导致组件渲染异常
  • 代码结构不完整,你直接把MaterialApp写在了类作用域,没有放在build方法中,拿不到正确的上下文加载本地化代理

正确实现步骤

  1. 恢复supportedLocales参数配置,禁止注释
  2. 修正State类的继承关系,补全build方法结构
  3. 如果需要在State生命周期中提前获取本地化实例,不要在initState中调用(此时上下文还未注入本地化代理),要在didChangeDependencies回调中获取

可运行的正确代码示例

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:provider/provider.dart';
// 替换为你自己项目中生成的本地化类路径
import 'l10n/app_localizations.dart';
import 'theme_notifier.dart';

class AnotherPage extends StatefulWidget {
  @override
  _AnotherPageState createState() => _AnotherPageState();
}

class _AnotherPageState extends State<AnotherPage> {
  AppLocalizations? _localizations;

  // 安全获取本地化实例的时机
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _localizations = AppLocalizations.of(context);
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<ThemeNotifier>(
      builder: (context, theme, child) => MaterialApp(
        debugShowCheckedModeBanner: false,
        theme: theme.getTheme(),
        locale: theme.getLocale(),
        // 必须配置支持的语言列表,不能注释
        supportedLocales: L10n.all,
        localizationsDelegates: const [
          AppLocalizations.delegate,
          GlobalMaterialLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
        ],
        home: Scaffold(
          appBar: AppBar(
            // 两种调用方式二选一即可
            title: Text(_localizations?.pageName ?? "加载失败"),
            // 也可以直接在build方法中实时获取:
            // title: Text(AppLocalizations.of(context)!.pageName),
          ),
        ),
      ),
    );
  }
}

额外注意

如果当前AnotherPage不是应用的根组件,上层已经存在配置好本地化参数的MaterialApp,就不要再嵌套MaterialApp了,重复配置会导致上下文层级混乱,直接在组件内调用AppLocalizations.of(context)即可拿到本地化值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 03:24:03