main(List
var name = null;
name ??= “lilei”;
print(name);
var name2 = null;
var temp = name2 ?? “lilei”;
print(temp);
}
级联运算符
main(List
var p = Person()
..name = “why”
..eat()
..running();
}
class Person {
String name = “”;
void eat() {
print(“eating”);
}
void running() {
print(“running”);
}
}
命名构造函数
main(List
var p = Person.withNameAgeHeight(“sss”, 12, 1.78);
print(p.age);
}
class Person {
String name;
int age;
double height = 0;
Person(this.name, this.age);
Person.withNameAgeHeight(this.name, this.age, this.height);
}
类初始化列表
main(List
}
class Person {
final String name;
final int age;
Person(this.name, {int age}) : this.age = age ?? 10 {}
}
构造函数的重定向
main(List
var p = Person(“why”);
print(p.age);
}
class Person {
String name;
int age;
Person(String name) : this._internal(name, 0);
Person._internal(this.name, this.age);
}
常量构造函数
main(List
const p1 = Person(“ss”);
const p12 = Person(“ss”);
print(identical(p1, p12));
}
class Person {
final String name;
const Person(this.name);
}
工厂构造函数
class People {
String name;
int age, sex;
static People _cache;
People() {
print(‘Dart —> People()’);
}
People.fromMap(map) {
this.name = map[‘name’];
this.age = map[‘age’];
this.sex = map[‘sex’];
print(‘Dart —> People.fromMap($map) —> $name, $age, $sex’);
}
factory People.map(map) {
if (People._cache == null) {
People._cache = new People.fromMap(map);
print(
‘Dart —> People.map($map) —> ${map[‘name’]}, ${map[‘age’]}, ${map[‘sex’]} —> People._cache == null’);
}
print(
‘Dart —> People.map($map) —> ${map[‘name’]}, ${map[‘age’]}, ${map[‘sex’]}’);
return People._cache;
}
factory People.fromJson(json) => People();
}