Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

with source_gen package, how can I get initializer value?

Tags:

dart

I would like to get the initializer in the field corrected_time in code below. I found the field.initializer, but couldn't get much further. (the @Init annotation is temporary solution for now):

mixin PrerenderDoc on Doc implements AllowDelete {
  @Init(init_int: 0)
  int corrected_time = 0;
}
like image 693
ChiNhan Avatar asked Sep 16 '25 05:09

ChiNhan


1 Answers

I'm guessing that field is an instance of FieldElement. Unfortunately, if that's the case, then the answer is that analyzer doesn't have a value for the initializer. The analyzer only computes values for (a subset of) expressions that are constant expressions. For field initializers, that means that the field needs to be declared to be const, and the one in the example isn't.

(Annotations are constants and hence have values, which is why your workaround works.)

If the field were declared const, then you could use VariableElement.constantValue to access a representation of the value (VariableElement is a superclass of FieldElement).

The other option available to you is to use the AST structure and examine the structure of the expression, but if you want / need to handle anything more than just simple literal values, that can be quite complex.

like image 133
Brian Wilkerson Avatar answered Sep 19 '25 14:09

Brian Wilkerson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!