Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the default value of an optional parameter, using Dart's analyzer API?

I'm using Dart's analyzer API, which allows me to introspect Dart code.

Here is some example code:

void soIntense(anything, {bool flag: true, int value}) {  }

Notice how the flag parameter has a default value of true.

How can I get the default value, assuming I have an instance of ParameterElement?

like image 205
Seth Ladd Avatar asked Sep 29 '22 19:09

Seth Ladd


1 Answers

Here's the best way that I found. I'm hoping there's a better way.

First, check that there is a default value:

bool hasDefaultValue = _parameter.defaultValueRange != null &&
       _parameter.defaultValueRange != SourceRange.EMPTY;

Then, you can use a ParameterElement's defaultValueRange.

SourceRange range = _parameter.defaultValueRange;
return _parameter.source.contents.data.substring(range.offset, range.end);

In english:

Get the parameter element's Source's content's data's substring.

like image 94
Seth Ladd Avatar answered Dec 31 '22 20:12

Seth Ladd