简体   繁体   中英

Dart Flutter: Syntax confusion in setting default value for class properties

Here are two examples of class constructors:

class A {
  final String name;
  final String sex;
  A({
    this.name = 'Unknown',
    this.sex = 'Unknown',
  });
}

Now consider the second class:

class B {
  final String name;
  final String sex;
  B({
    this.name = 'Unknown',
    sex,
  }) : sex = name == 'Unknown' ? 'Unknown' : 'Other';
}

I am confused as to if the second example is considered as an alternative to the first example's syntax or is it intended for a whole different purpose?

The first example allows "sex" to be any value given to the constructor.

The second example however only accepts the default ("Unknown", and sets "sex" to "Other" for any value given other than "Unknown".

So a = A(name:"Jon", sex:"male") result in a.sex == "male" , whereas b = B(name:"Jon", sex:"male") result in b.sex == "Other" .

If defaults are used, as in x = A(name:"Joe") , or x = B(name:"Joe") the resulting objects will both have x.sex == "Unknown"

From what I could gather and since I received no satisfying answer/comment, here is what I ended up accepting as a difference.

The first example's syntax allows for assigning a default value to a property when that value is a single non-conditional value.

However, if one needs to assign a value based on a condition -like in the case of the second example, a ternary operator- it won't be possible to do that following the first syntax because it will result in an error, so the variable must be initialized according to the second syntax.

Please correct me if I am wrong.

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