dart-lang / code_builder

A fluent API for generating valid Dart source code
https://pub.dev/packages/code_builder
BSD 3-Clause "New" or "Revised" License
423 stars 66 forks source link

Darttype.element as ClassElement, but element2 was prompted after the upgrade #374

Closed xiaocode337317439 closed 1 year ago

xiaocode337317439 commented 1 year ago

Darttype. element as ClassElement Not sure how to convert to ClassElement after using element2 ?

        final ele = type.element as ClassElement; // type => DartType
        // final ele = type as InterfaceType;
        final toJson = ele.lookUpMethod('toJson', ele.library);
        // final toJson = ele.getMethod("toJson");
        if (toJson == null) {
          value = refer("jsonEncode($displayName)");
        } else {
          value = refer("$displayName?.toJson()");
        }
srawlins commented 1 year ago

CC @scheglov

scheglov commented 1 year ago

InterfaceType.element2 is InterfaceElement, and will be in future version not only ClassElement, but also EnumElement, or MixinElement. Right now both are also ClassElement, but we will separate them in the next breaking changes version. I think you might use InterfaceElement methods, without casting to ClassElement.

xiaocode337317439 commented 1 year ago

InterfaceType.element2 is InterfaceElement, and will be in future version not only ClassElement, but also EnumElement, or MixinElement. Right now both are also ClassElement, but we will separate them in the next breaking changes version. I think you might use InterfaceElement methods, without casting to ClassElement.

How should DartType be converted to InterfaceType?

xiaocode337317439 commented 1 year ago

InterfaceType.element2 is InterfaceElement, and will be in future version not only ClassElement, but also EnumElement, or MixinElement. Right now both are also ClassElement, but we will separate them in the next breaking changes version. I think you might use InterfaceElement methods, without casting to ClassElement.

How should DartType be converted to InterfaceType?

TypeChecker(List).isExactly((ParameterElement.type as InterfaceElement))

error => type 'ParameterElementImpl' is not a subtype of type 'InterfaceElement' in type cast
scheglov commented 1 year ago

You don't convert, you check if it is InterfaceType, using if (myType is InterfaceType) {...}. It might be something different, e.g. FunctionType.

xiaocode337317439 commented 1 year ago

You don't convert, you check if it is InterfaceType, using if (myType is InterfaceType) {...}. It might be something different, e.g. FunctionType.

Thank you for answering