首页 > 解决方案 > dart 命名构造函数的 IntelliJ 实时模板:列出类的字段

问题描述

我想在 Dart 中生成一个自定义命名构造函数。我有许多要实现的 dto 类,每个类都应该提供一个命名构造函数,例如:ClassName.fromMap()

例如这个类:

class Student {
  final String name;
  final int age;
}

生成的构造函数应该是:

Student.fromMap(Map<String, dynamic> map) :
    name = map['name'],
    age = map['age'];

如何将当前类的字段列表检索为字符串?这甚至可能吗?
当然,我可以有可变数量的字段。

我的模板看起来像:

$CLASS$.fromMap(Map<String, dynamic> map) :
        $INITIALIZATION_LIST$

绑定$CLASS$dartClassName().

现在我想绑定$INITIALIZATION_LIST$到类似的东西:

getClassFieldList().forEach((fieldName) => "$fieldName = map['$fieldName']")

我可以实现这样的目标吗?

标签: android-studiointellij-ideadartlive-templates

解决方案


无法使用预定义的实时模板函数检索 Dart 类字段列表。您可以尝试为此开发自己的模板宏。有关一些提示,请参阅https://intellij-support.jetbrains.com/hc/en-us/community/posts/206201699-create-a-new-expression-for-a-live-template-for-actionscript。可以在https://github.com/JetBrains/intellij-community/tree/master/platform/lang-impl/src/com/intellij/codeInsight/template/macro找到现有的实时模板函数实现。

您也可以尝试使用结构搜索和替换而不是实时模板


推荐阅读