简体   繁体   English

使用 dart 中的分析器检查构造函数元素

[英]Check constructor element with analyzer in dart

I created a library in Flutter to generate code for the annotated elements.我在 Flutter 中创建了一个库来为带注释的元素生成代码。 I need to check the parameter in the constructor of class is required using analyzer.我需要使用分析器检查类的构造函数中的参数是否需要。

Example of widget with annotation:带注释的小部件示例:

@myAnnotation
class WidgetText extends StatelessWidget {
  WidgetText({
    @required this.text,
    this.subtitle,
  });

  final String text;
  final String subtitle;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text(text),
        if (subtitle != null) Text(subtitle),
      ],
    );
  }
}

Example of my visitor:我的访客示例:

class MyAnnotationVisitor extends SimpleElementVisitor<void> {
  @override
  void visitFieldElement(FieldElement element) {
    print('${element.name} is required? ${element.hasRequired}');
  }
}

This visitor above output this for WidgetText上面的这个访问者为WidgetText输出这个

text is required? false
subtitle is required? false

The visitor can verify if the field is required only when an annotation is marked on the field this way below.仅当在字段上以这种方式标记注释时,访问者才能验证是否需要该字段。 But is repetitive and I would like to check in the constructor.但是是重复的,我想检查构造函数。

@myAnnotation
class WidgetText extends StatelessWidget {
  WidgetText({
    @required this.text,
    this.subtitle,
  });

  @required
  final String text;
  final String subtitle;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text(text),
        if (subtitle != null) Text(subtitle),
      ],
    );
  }
}

This is possible analyzing ParameterElement .这是可能的分析ParameterElement Has a get called hasRequired .有一个叫做hasRequired

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM