@
ufan0 作为同时写 Flutter 和 iOS 原生的吐槽几点 Dart:
1.枚举不能忽略名称,静态变量(方法)不能忽略类名
```dart
currentConnectivityType: ConnectivityResult.wifi 👎
currentConnectivityType: .wifi 👍
```
```dart
return Container(color: Colors.white, ... 👎
return Container(color: .white, ... 👍
```
2.函数方法默认值鸡肋
有默认值的参数必须使用 `{}` 包起来,而且必须放在方法的最后,甚至默认值只能是常量 😵💫
```dart
void foo(int arg1, { int arg2 = 0, int arg3 = 0 }) 👎
void foo(int arg1 = 0, int arg2, int arg3 = 0) 👍
```
3.必须显性的书写 const
`EdgeInsets.only(top: 8)` 显然是一个常量,为何需要显性的写上 `const`,而不是编译器或 IDE 自动处理
```dart
padding: const EdgeInsets.only(top: 8) 👎
padding: .only(top: 8 ) 👍
```
4.残缺的 Optional ?
```dart
class Foo {
final int? count;
void test() {
if (count != null) {
count += 1; ❌
count! += 1; ❌
}
}
}
上面的代码无法编译通过,因为 count 定义为 `int?`,即使已经判断了非空,获取它之前仍然需要 `unwrap`,只能写:
count = count! + 1; 😅
```
5.异常处理理念落后
下面是个经典的 Dart 异常处理流程,存在 2 个问题:
- 可能抛出异常的方法没有明显的标志,只能依靠文档和阅读源码来确定这个方法是否会抛出异常,因此调用时很难确定一个方法是否需要` try catch`
- try 的 {} 内通常包含多个方法的组合调用,除非查看各个方法的实现,否则很难判断出哪些方法是会抛出异常的
```dart
// 定义一个可能抛出异常的方法
void functionCanThrowException() {
....
throw Exception('xxxxxxx');
}
// 调用
try {
functionA();
functionB();
functionCanThrowException();
functionC();
} catch(e) {
// handle error
}
```
6.反人类的 json 序列化
竟然需要借助 json_serializable 之类的插件才能完成其他语言自动实现的功能,生成一大堆 .g.dart 文件更是丑陋