简体   繁体   English

Dart:Dart如何与Class的Constructor中的命名参数匹配?

[英]Dart: How does Dart match the named parameters in a Constructor of a Class?

How does Dart match the named parameters in a Constructor of a Class? Dart如何在类的构造函数中匹配命名的参数?

Example (which works) : 示例(有效):

Class MyWidget {

    final String a;
    final String b;

    MyWidget (
        @required this.a,
        @required this.b
    )

    @override // Yes, it's Flutter
    Widget build(BuildContext context) {
        return ....
    }
}


/// Calling MyWidget
return MyWidget(
    a: x,
    b: y
)

This works as expected. 这按预期工作。 But in this setup I am forced to name the variable in MyWidget the same as the Named Parameter because the 'a' in the call is the same as the 'this.a' in the MyWidget. 但是在此设置中,由于调用中的“ a”与MyWidget中的“ this.a”相同,因此我不得不在MyWidget中将变量命名为“命名参数”。

What I would like is something like this: 我想要的是这样的:

Class MyWidget {

   final String aaa;
   final String bbb;

   MyWidget (
       @required a // And assign that value to this.aaa,
       @required b // And assign that value to this.bbb
   )
}

How do I assign the value of passed Named Parameter 'a' to local variable 'aaa'? 如何将传递的命名参数“ a”的值分配给局部变量“ aaa”?

You have to trade off the simplicity of the this.xxx syntax like this: 您必须权衡this.xxx语法的简单性,如下所示:

class MyWidget {
  final String aaa;
  final String bbb;

  MyWidget({a, b})
      : aaa = a,
        bbb = b;
}

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

相关问题 在 Dart 类构造函数中使用可选命名参数的正确方法 - Right way of using optional named parameters in Dart class constructor Dart 构造函数中的必需参数可以命名吗? - Can required parameters in a Dart constructor be named? 具有命名构造函数的Dart抽象类通用类型 - Dart Abstract class of Generic Type with Named Constructor Dart,带有命名参数的构造函数不起作用。 预期位置参数 - Dart, constructor with named parameters not working. Positional parameters expected 在运行时选择要包含在 dart class 构造函数中的命名参数 - Choosing which named parameters to include in a dart class constructor at run-time 如何在 Dart 中使用命名参数在构造函数初始化列表中创建最终成员变量? - How to create a final member variable in the constructor initialization list using named parameters in Dart? Dart 中的构造函数的命名为 arguments 的 inheritance - inheritance of named arguments of constructor in Dart Dart:Class 构造函数未调用 - Dart : Class Constructor not called dart 命名构造函数的 IntelliJ 实时模板:列出类的字段 - IntelliJ Live Template for dart named constructor: lists class' fields 如何在构造函数上使用命名参数的Dart类中添加吸气剂? - How can I add a getter to a Dart class with a named parameter on its constructor?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM