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

Flutter中AppLocalizations.of(context)报错:'of'重复声明问题

问题解决:Flutter本地化of命名冲突错误

问题描述

之前正常运行的代码:

Widget build(BuildContext context) {
  AppLocalizations localizations = AppLocalizations.of(context)!;
}

突然出现以下错误:

Waiting for connection from debug service on Chrome...
.dart_tool/flutter_gen/gen_l10n/app_localizations.dart:490:14: 错误:'of' 已在此作用域中声明。
String get of;
^^
.dart_tool/flutter_gen/gen_l10n/app_localizations.dart:67:28: 上下文:'of' 的先前声明。
static AppLocalizations? of(BuildContext context) {
^^
lib/screens/main-page/components/appbar.dart:25:55: 错误:无法使用 'of',因为它被多次声明。
AppLocalizations localizations = AppLocalizations.of(context)!;
^^
lib/screens/shared_components/mskn_drawer.dart:18:55: 错误:无法使用 'of',因为它被多次声明。
AppLocalizations localizations = AppLocalizations.of(context)!;
^^
lib/screens/main-page/components/search_field.dart:18:55: 错误:无法使用 'of',因为它被多次声明。
AppLocalizations localizations = AppLocalizations.of(context)!;
^^
lib/screens/main-page/components/suggestion_list.dart:26:55: 错误:无法使用 'of',因为它被多次声明。
AppLocalizations localizations = AppLocalizations.of(context)!;
^^
lib/screens/other/about_us.dart:16:55: 错误:无法使用 'of',因为它被多次声明。
AppLocalizations localizations = AppLocalizations.of(context)!;
^^
lib/screens/other/connect_with_us.dart:19:55: 错误:无法使用 'of',因为它被多次声明。
AppLocalizations localizations = AppLocalizations.of(context)!;
^^
lib/screens/main-page/components/buildings_cards.dart:23:55: 错误:无法使用 'of',因为它被多次声明。
AppLocalizations localizations = AppLocalizations.of(context)!;
^^

原因分析

这是因为你的本地化资源文件(如app_en.arb、app_zh.arb等)中存在一个名为of的键,flutter_gen工具在生成本地化代码时,会将这个键转换为String get of;的getter方法,而AppLocalizations类原本就有一个静态方法static AppLocalizations? of(BuildContext context),两者名称完全一致,导致命名冲突。

解决步骤

  1. 修改本地化资源文件:打开所有的.arb本地化文件,找到键名为"of"的条目,将其重命名为不冲突的名称(比如"ofText"、"ofDescription"等)。例如:
    原条目:

    "of": "的"
    

    修改后:

    "ofText": "的"
    
  2. 清理并重新生成代码:

    • 执行命令清理项目:flutter clean
    • 获取依赖并重新生成本地化代码:flutter pub get
    • 重新运行你的Flutter项目
  3. 更新代码中的调用(如果有):如果之前有代码调用localizations.of来获取这个文本,现在需要改成新的名称,比如localizations.ofText。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 21:15:36