# 语法使用收集
# const
# 使用 const 调用组件
Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
const SizedBox(height: 8.0),
],
)
1
2
3
4
5
6
7
2
3
4
5
6
7
在这种情况下,使用 const 调用,会让这个子组件在父组件的状态改变时不再被渲染
TIP
除了第一次渲染外,不再触发 const 调用的这个子组件的 build 方法,节省性能,提高用户体验。
其实没啥用,所以如上文提到。在 Dart 2 中,也已经变成可选的了。
# const 声明构造方法
TIP
在声明一个类/组件的构造方法时,也可以使用 const。用了 const 的,叫“常量构造函数”。
- 如果一个类中,只包含使用 final 关键字声明的属性( 即实例化后不会再发生变化的属性 ),而且这个构造函数出了初始化这些属性之外什么都不做,那么你就可以用 const 关键字来声明构造函数。
- 我们知道,常量(或者编译时常量、运行时常量)存在的目的,就是为了减少性能损耗。同理,常量构造函数也是为了降低性能的损耗。
- 所以,如果你能够保证,在这个类中只设置 final 声明的属性,甚至没有属性。你就应该尽量使用常量构造函数。
TIP
常量构造函数对用于简单的、或者不可变的数据记录的类时非常有用。
# List
# firstWhere
E firstWhere(bool test(E element), {E orElse()?}) {
for (E element in this) {
if (test(element)) return element;
}
if (orElse != null) return orElse();
throw IterableElementError.noElement();
}
1
2
3
4
5
6
7
2
3
4
5
6
7
PasswordCategory passwordCategory = PasswordCategory.values.firstWhere(
(element) => element.name == category,
orElse: () => PasswordCategory.unknown);
1
2
3
2
3
# MaterialStateProperty
# MaterialStateProperty.all()
方法是设置点击事件所有状态下的样式
# MaterialStateProperty.resolveWith()
可拦截分别设置不同状态下的样式
foregroundColor: MaterialStateProperty.resolveWith(
(states) {
if (states.contains(MaterialState.focused) &&
!states.contains(MaterialState.pressed)) {
//获取焦点时的颜色
return Colors.blue;
} else if (states.contains(MaterialState.pressed)) {
//按下时的颜色
return Colors.deepPurple;
}
//默认状态使用灰色
return Colors.grey;
},
),
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# ButtonStyle
style: ButtonStyle(
//定义文本的样式 这里设置的颜色是不起作用的
textStyle: MaterialStateProperty.all(
TextStyle(fontSize: 18, color: Colors.red)),
//设置按钮上字体与图标的颜色
//foregroundColor: MaterialStateProperty.all(Colors.deepPurple),
//更优美的方式来设置
foregroundColor: MaterialStateProperty.resolveWith(
(states) {
if (states.contains(MaterialState.focused) &&
!states.contains(MaterialState.pressed)) {
//获取焦点时的颜色
return Colors.blue;
} else if (states.contains(MaterialState.pressed)) {
//按下时的颜色
return Colors.deepPurple;
}
//默认状态使用灰色
return Colors.grey;
},
),
//背景颜色
backgroundColor: MaterialStateProperty.resolveWith((states) {
//设置按下时的背景颜色
if (states.contains(MaterialState.pressed)) {
return Colors.blue[200];
}
//默认不使用背景颜色
return null;
}),
//设置水波纹颜色
overlayColor: MaterialStateProperty.all(Colors.yellow),
//设置阴影 不适用于这里的TextButton
elevation: MaterialStateProperty.all(0),
//设置按钮内边距
padding: MaterialStateProperty.all(EdgeInsets.all(10)),
//设置按钮的大小
minimumSize: MaterialStateProperty.all(Size(200, 100)),
//设置边框
side:
MaterialStateProperty.all(BorderSide(color: Colors.grey, width: 1)),
//外边框装饰 会覆盖 side 配置的样式
shape: MaterialStateProperty.all(StadiumBorder()),
),
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44