Dart构造函数和?操作符

249 阅读1分钟
// 构造函数分为有名和匿名,匿名构造函数只能有一个。
class MyEmptyClass  {
final int myNum;
//匿名构造函数
MyEmptyClass(this.myNum)
    : assert(true),
      super();
//有名构造函数
MyEmptyClass.withName(this.myNum, {String value = 'optional'}) : super();

// :后面可以跟成员变量初始化,父类初始化,assert,redirect
// 不能跟print('init');这种函数
// 构造函数空实现,可以省略{},但要用;结尾.
MyEmptyClass.withInit(String required)
    : myNum = 2,
      super();

MyEmptyClass.withInitAndSomething(String from)
    : myNum = 2,
      super() {
  print('init');
}

MyEmptyClass.redirect (String from)
  : this.withInitAndSomething(from);

}

// ?号分解理解
var hasValue = false;
var value = hasValue ? 1 : 0; //三元操作符
Key someValue;
var keyvalue = hasValue ? 1 : 0; //可以使用普通对象作为三元操作符的判断对象
String name1 = someValue?.toString(); //检查空对象,避免空指针,结果返回null
print(name1);
String name2 = someValue ?? "empty"; // 空对象赋默认值
var myKey = someValue ?? Key("x");
someValue ??= Key("empty"); //为空赋值
print('someValue:' + someValue.toString());

//相关源码展示
Container({
  Key key,
  this.alignment,
  this.padding,
  Color color,
  Decoration decoration,
  this.foregroundDecoration,
  double width,
  double height,
  BoxConstraints constraints,
  this.margin,
  this.transform,
  this.child,
}) : assert(margin == null || margin.isNonNegative),
     assert(padding == null || padding.isNonNegative),
     assert(decoration == null || decoration.debugAssertIsValid()),
     assert(constraints == null || constraints.debugAssertIsValid()),
     assert(color == null || decoration == null,
       'Cannot provide both a color and a decoration\n'
       'The color argument is just a shorthand for "decoration: new BoxDecoration(color: color)".'
     ),
     decoration = decoration ?? (color != null ? BoxDecoration(color: color) : null),
     constraints =
      (width != null || height != null)
        ? constraints?.tighten(width: width, height: height)
          ?? BoxConstraints.tightFor(width: width, height: height)
        : constraints,
     super(key: key);
     ```