【问题标题】:Flutter Dynamic object fieldnameFlutter 动态对象字段名
【发布时间】:2023-02-26 11:11:34
【问题描述】:

我想为我的 riverpod_hook 项目创建一个动态小部件,例如

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

我正在尝试类似的东西

class TrText extends StatelessWidget {
  const TrText({
    super.key,
    required this.value,
    required this.fieldName,
    required this.placeHolder,
    this.textStyle,
  });
  final AsyncValue<Translation> value;
  final TextStyle? textStyle;
  final String placeHolder;
  final String fieldName;

  @override
  Widget build(BuildContext context) {
    return value.when(
      data: (Translation tr) => Text(
        tr.fieldName ?? placeHolder,
        style: textStyle,
      ),
      error: (error, stackTrace) => Text(placeHolder),
      loading: () => const SecondaryLoader(),
    );
  }
}

我的翻译类代码:

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,
      });
}

现在我得到“getter 'fieldName' 没有为类型 'Translation' 定义。”错误。

【问题讨论】:

    标签: flutter dart riverpod


    【解决方案1】:

    当您在Text中使用fieldName时,您错误地引用了tr

    @override
      Widget build(BuildContext context) {
        return value.when(
          data: (Translation tr) => Text(
            fieldName ?? placeHolder,//tr.fieldName ?? placeHolder
            style: textStyle,
          ),
          error: (error, stackTrace) => Text(placeHolder),
          loading: () => const SecondaryLoader(),
        );
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-18
      • 1970-01-01
      • 2021-06-21
      • 2011-05-25
      • 2018-04-07
      • 2012-10-04
      • 1970-01-01
      相关资源
      最近更新 更多