source_gen icon indicating copy to clipboard operation
source_gen copied to clipboard

How to get a reference of a type from my element attribute to create an import statement?

Open atreeon opened this issue 5 years ago • 1 comments

I am generating code from a function

@mycodegen
List<Cat> getCats() {
  return cats;
}

I need now to get an import statement when I reproduce the call method when generating code in my library builder, otherwise a reference to Cat will be missing. I can do this in the generator:

callMethod.type.returnType.element.location

which produces something like

asset:example/test/Cat.dart;asset:example/test/Cat.dart;Cat

I would then have to do some string manipulation to get the bits I want to create an import statment. Is this best practice or is there an easier way?

atreeon avatar Feb 08 '21 19:02 atreeon

You can get an AssetId through the assetIdForElement api which would give you a bit more directly what you need.

That has a uri getter, but it will only give an "importable" uri if it can be mapped to a package: uri. If it comes from something outside of a lib directory you would have to construct a relative path to it using the path property of the asset id.

jakemac53 avatar Feb 08 '21 20:02 jakemac53