函数入参的默认值
// 示例
class Person {
String? language;
String? nation;
String? name;
int? age;
Person(this.name, this.age);
// 带有默认参数的入参需要被放在参数列表的最后,并且用 {} 包裹起来,表示为可选参数
Person.Chinese(String name, int age, {String nation = "Chinese", String language = "Mandarin"}) {
this.name = "name";
this.age = 0;
}
}
构造函数
有三种构造函数,默认构造函数、命名构造函数、带有初始化列表的构造函数
class Person {
String? language;
String? nation;
String? name;
int? age;
// 1. 默认构造函数
Person(this.name, this.age);
// 2. 命名构造函数
Person.Chinese(String name, int age, {String nation = "Chinese", String language = "Mandarin"}) {
this.name = "name";
this.age = 0;
}
// 3. 构造函数 + 初始化列表
Person.USA(String name, int age, {String nation = "English", String language = "English"}) : this.name = name, this.age = age, language = "", nation = "" {
this.name = "United States Of America";
}
}
带有初始化列表的构造函数被:隔开分两部分。:的后半部分是初始化列表部分,用来初始化成员变量,且初始化列表执行时机早于初始化函数的函数体
。
void main() {
Person usa = Person.USA("USA", 18);
print("${usa.name}"); // 输出: United States Of America
}
异步回调
两种方式:1. 通过 <async await> 构造异步回调 2. 通过 <回调函数> 构造异步回调
void main() {
asyncfoo();
print("========");
blockfoo();
}
asyncfoo() {
print("== start ==");
var result = _asyncfoo();
print(result);
print("== end ==");
}
// 通过 <async await> 构造异步回调
Future _asyncfoo() async {
await Future.delayed(const Duration(seconds: 2));
return Future.value("Result String ->> _asyncfoo");
}
void blockfoo() {
print("== start ==");
_blockfoo((value) {
print(value);
});
print("== end ==");
}
// 通过 <回调函数> 构造异步回调
Future<void> _blockfoo(Function(String) callback) async {
await Future.delayed(const Duration(seconds: 2));
callback("Result String ->> _blockfoo");
}
enum
enum GMBottomNavigationBarModule {
discovery,
vehicle,
profile,
discoveryScrollback; //this enum will be display, it's other state of
static GMBottomNavigationBarModule module(int index) =>
GMBottomNavigationBarModule.values
.firstWhere((element) => element.index == index);
bool get isDiscovery {
switch (this) {
case GMBottomNavigationBarModule.discovery:
case GMBottomNavigationBarModule.discoveryScrollback:
return true;
case GMBottomNavigationBarModule.vehicle:
case GMBottomNavigationBarModule.profile:
return false;
}
}
List
sort
高阶函数map/reduce/where,where 类比于 swift 的 filter
class Person {
int age;
Person(this.age);
String toString() {
return "age is ${this.age}";
}
}
void main() {
List<Person> persons = [
Person(10),
Person(20),
Person(30),
];
// Map
var newLists = persons.map((e) => e.age + 1);
print(newLists); // output: 11, 21, 31
// Reduce
var ageSum = persons.map((e) => e.age).reduce((a,b) => a + b);
print(ageSum); // output: 60
// Where 类似 swift 的 filter
var overTenList = persons.where((a) => a.age > 10).toList();
print(overTenList); // output: [age is 20, age is 30]
}
网友评论