【问题标题】:How to work with classes extended from EnumClass and generated by build_runner in Dart/Flutter?如何使用从 EnumClass 扩展并由 Dart/Flutter 中的 build_runner 生成的类?
【发布时间】:2022-01-13 07:48:55
【问题描述】:

为了将我的 GraphQL 架构转换为 Dart 类,我使用了 Ferry 包,并使用 build_runner 运行它。

在我的数据库中,我定义了以下 enum 类型:

CREATE TYPE my_schm.currency AS ENUM ('CNY','EUR','PEN','USD');

这是它的翻译(来自schema.schema.gql.dart):

class GCurrency extends EnumClass {
  const GCurrency._(String name) : super(name);

  static const GCurrency CNY = _$gCurrencyCNY;

  static const GCurrency EUR = _$gCurrencyEUR;

  static const GCurrency PEN = _$gCurrencyPEN;

  static const GCurrency USD = _$gCurrencyUSD;

  static Serializer<GCurrency> get serializer => _$gCurrencySerializer;
  static BuiltSet<GCurrency> get values => _$gCurrencyValues;
  static GCurrency valueOf(String name) => _$gCurrencyValueOf(name);
}

这个类又用于:

class GCreateQuoteRequestVarsBuilder
    implements
        Builder<GCreateQuoteRequestVars, GCreateQuoteRequestVarsBuilder> {
  _$GCreateQuoteRequestVars? _$v;

....
  _i2.GCurrency? _currency;
  _i2.GCurrency? get currency => _$this._currency;
  set currency(_i2.GCurrency? currency) => _$this._currency = currency;
....
}

我正在尝试实现以下请求方法(为清楚起见,省略了一些变量):

  GCreateQuoteRequestReq createQuoteRequest(List<Object> values) => GCreateQuoteRequestReq(
    (b) => b
      ..vars.vehicle = values[0] as String
      ..vars.body = values[1] as String
      ..vars.currency = values[5] as GCurrency
  );

values[5]有问题,是String类型,我需要把它强制转换成正确的类型,应该是GCurrency,但是我收到此错误:

The name 'GCurrency' isn't a type, so it can't be used in an 'as' expression.
Try changing the name to the name of an existing type, or creating a type with the name 'GCurrency'.

根据文档,我只需要为我的任务导入以下文件:

import '../loggedin.data.gql.dart';
import '../loggedin.req.gql.dart';
import '../loggedin.var.gql.dart';

【问题讨论】:

  • 你应该可以使用GCurrency这个类。可以vars.currency = GCurrency.valueOf(values[5])吗?
  • 谢谢兄弟,你能发表你的评论作为答案吗?这样你就可以获得赏金了。

标签: flutter dart enums build-runner


【解决方案1】:

您应该可以使用GCurrency 类。可以vars.currency = GCurrency.valueOf(values[5])吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-26
    • 1970-01-01
    • 2020-04-27
    • 2020-06-19
    • 1970-01-01
    • 2020-02-22
    • 2018-05-12
    • 2012-09-23
    相关资源
    最近更新 更多