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

Flutter Riverpod Hook项目动态访问Translation字段报错求助

问题解决:The getter 'fieldName' isn't defined for the type 'Translation'

错误原因

你代码里的tr.fieldName是试图直接访问Translation类的fieldName属性,但你的Translation类并没有定义这个属性。实际需求是根据传入的字符串参数fieldName(比如'newPassword'),获取Translation对象中对应的属性值(比如tr.newPassword),直接写tr.fieldName属于语法错误。

解决方案

提供两种可行的解决方式,任选一种即可:

方式一:给Translation类添加取值方法

修改你的Translation类,新增一个根据字段名返回对应翻译值的方法:

class Translation {
  final int? id;
  final String? profile;
  final String? changePassword;
  final String? login;
  final String? logout;
  final String? oldPassword;
  final String? newPassword;

  Translation({
    this.id,
    this.profile,
    this.changePassword,
    this.login,
    this.logout,
    this.oldPassword,
    this.newPassword,
  });

  // 新增方法:根据字段名获取对应翻译内容
  String? getTranslation(String fieldName) {
    switch(fieldName) {
      case 'profile':
        return profile;
      case 'changePassword':
        return changePassword;
      case 'login':
        return login;
      case 'logout':
        return logout;
      case 'oldPassword':
        return oldPassword;
      case 'newPassword':
        return newPassword;
      default:
        return null;
    }
  }
}

然后修改TrText组件的data分支代码:

data: (Translation tr) => Text(
  tr.getTranslation(fieldName) ?? placeHolder,
  style: textStyle,
),

方式二:在TrText组件内使用映射匹配

不需要修改Translation类,直接在TrText的build方法里创建字段名与属性的映射:

@override
Widget build(BuildContext context) {
  return value.when(
    data: (Translation tr) {
      final fieldMapping = {
        'profile': tr.profile,
        'changePassword': tr.changePassword,
        'login': tr.login,
        'logout': tr.logout,
        'oldPassword': tr.oldPassword,
        'newPassword': tr.newPassword,
      };
      return Text(
        fieldMapping[fieldName] ?? placeHolder,
        style: textStyle,
      );
    },
    error: (error, stackTrace) => Text(placeHolder),
    loading: () => const SecondaryLoader(),
  );
}

额外提醒

你示例调用代码里有个拼写错误:fliedName应该改为fieldName,否则会出现传参不匹配的问题,正确调用应为:

final value = ref.watch(trProvider);
TrText(value: value, fieldName: 'newPassword', placeHolder: 'New Password'); 

内容的提问来源于stack exchange,提问作者Tanvir Ibn Mizan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 04:43:25