Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with classes extended from EnumClass and generated by build_runner in Dart/Flutter?

For converting my GraphQL schema into Dart classes, I'm using the Ferry package, and I run this using build_runner.

In my database, I've defined the following enum type:

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

Here is a translation of it (from 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);
}

This class, in turn, is used to:

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;
....
}

I am trying to implement the following request method (some variables have been omitted for clarity):

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

There is a problem with values[5], which is a String type, and I need to cast it to the right type, which should be GCurrency, but I'm getting this error:

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'.

According to documentation I need to import the following files only for my tasks:

import '../loggedin.data.gql.dart';
import '../loggedin.req.gql.dart';
import '../loggedin.var.gql.dart';
like image 879
Ουιλιαμ Αρκευα Avatar asked Oct 14 '22 19:10

Ουιλιαμ Αρκευα


1 Answers

You should be able to use the class GCurrency. Can you vars.currency = GCurrency.valueOf(values[5])?

like image 186
Michele Volpato Avatar answered Oct 20 '22 16:10

Michele Volpato