Mastering Development

Get name of undefined super type or interface with source_gen

I’m working on a builder package and would like access to the class name defined as the super constraint. When first building, it won’t exist so I’m guessing source_gen just excludes it from its analysis

For example, considering I require the user to define

class User extends _$User {
  final UserBase data;

    required DocumentSnapshot snapshot,
  }) : super(snapshot);

  factory User.fromSnapshot(DocumentSnapshot snapshot) =>

How do I get the name of the as yet undefined class _$User? I want to be dynamic so even if the user decides to name it something else I can adapt to that name.

I’ve tried most fields on the element but can’t find anything that would give me it:

FutureOr<String> generateForAnnotatedElement(
  Element element,
  ConstantReader annotation,
  BuildStep buildStep,
) async {
  final classElement = element as ClassElement;

  classElement.supertype; // Object
  classElement.displayName; // class User

  // I want _$User somehow

Maybe the answer involves getting the ast but I’m not super experienced with that.

Leave a Reply

Your email address will not be published. Required fields are marked *