简体   繁体   中英

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?

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.

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'?

You have to trade off the simplicity of the this.xxx syntax like this:

class MyWidget {
  final String aaa;
  final String bbb;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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