dart的语法糖和一些trick
知道这些tips,可以写出更简洁的代码
1.string的乘法
1 | void main() { |
2.同步调用Future函数
1 | //演示数据 |
使用Future.wait
1 | final api = CovidAPI(); |
3.类里的call方法
1 | class PasswordValidator { |
可以像方法一样直接通过实例对象调用,
两种调用方式
1 | final validator = PasswordValidator(); |
4用”?.call()”调用回调函数避免为空
1 | //demo类 |
这是传统写法
1 | void _dragComplete() { |
另一种简便写法,为null就不会调用了,和上面等效
1 | Future<void> _dragComplete() async { |
5.函数作为参数传递
dart里函数也是一等公民,具有和其他变量同等待遇
1 | void main() { |
6.容器判断和容器展开
…可以把容器的元素展开,也可以在容器里添加if判断语法
1 | const addRatings = true; |
7.安全遍历map”.entries”
1 | for (var entry in timeSpent.entries) { |
比遍历key安全
1 | for (var key in timeSpent.keys) { |
这个实现如果key对应的value是null,就会报错
8.使用命名构造函数,更具有维护性,可读性
1 | class Temperature { |
9.Getter和Setter
dart里的getter和setter的语法
1 | class Temperature { |
1 | final temp1 = Temperature.celsius(30); |
10.用_
下划线代替未使用的参数
1 | class MyListView extends StatelessWidget { |
如果不使用context,index,可以写成如下
1 | istView.builder( |
_和__代表不同的参数
11.单例实现
dart的单例实现方式
1 | // file_system.dart |
无法实例化,仅能通过以下方式访问
1 | // some_other_file.dart |
12.Set
如果需要一个不包含重复元素的集合,那么使用Set
一个细节,如果使用final 修饰set,有重复元素只会提示warning
1 | // set is final, compiles |
如果用const修复,会提示无法编译
1 | // set is const, doesn't compile |
TODO
15. Common Stream constructors
The Stream class also comes with some handy constructors. Here are the most common ones:
1 | Stream.fromIterable([1, 2, 3]); |
- use
Stream.fromIterable
to create aStream
from a list of values. - use
Stream.value
if you have just one value. - use
Stream.empty
to create an empty stream. - use
Stream.error
to create a stream that contains an error value. - use
Stream.fromFuture
to create a stream that will contain only one value, and that value will be available when the future completes. - use
Stream.periodic
to create a periodic stream of events. You can specify aDuration
as the time interval between events, and an anonymous function to generate each value given its index in the stream.
16. Sync and Async Generators
In Dart we can define a synchronous generator as a function that returns an Iterable
:
1 | Iterable<int> count(int n) sync* { |
This uses the sync*
syntax. Inside the function we can “generate” or yield
multiple values. These will be returned as an Iterable
when the function completes.
On the other hand, an asynchronous generator is a function that returns a Stream
:
1 | Stream<int> countStream(int n) async* { |
This uses this async*
syntax. Inside the function we can yield
values just like in the synchronous case.
But if we want we can await
on Future-based APIs, because this is an asynchronous generator:
1 | Stream<int> countStream(int n) async* { |
转自