[Flutter] 6个你该知道的Dart诀窍

最近有新开一个部落格是在介绍Flutter相关的文章,大家可以去看看~

1.同时执行多个Future Function

当你想要同时呼叫多个Api时,如果他们之间彼此没有一定的顺序性时,你可以这样做:

await Future.wait([    function1(),    function2(),    function3(),]);

这样就不用一个一个等待了!

2.当在宣告list,set和map参数时,可以加入判断参数

const shouldHavePhoneNum = true;const userContact = {    'name': 'James',    'age': 23,    if (shouldHavePhoneNum) ... {        'phone': '09123456789',        'tel': '02123456'    }}

3.在递迴map时使用 '.entries'

假设有一个map:

const map = <String, String>{    'Tom': '091111111',    'James': '09222222',    'Annie': '093333333'};

比较好的递迴方式是:

for (var entry in map.entries) {    print('${entry.key}\'s phone number is ${entry.value}');}

这样就能确保每个值都是non-null的。

如果是用key的方式去拿值,则必须检查是否为null

for (var key in map.keys) {    final phone = map[key]!; <-- 强制为non-null, 或是需要额外检查    print('$key\'s phone number is $phone');}

4.一个class只有一个实例(instance),也就是Singleton

这边先不讨论使用Singleton的时机以及可能带来的影响,也有很多种做Singleton的方式,这边提供其中一种方式:

class Singleton {    Singleton._();    static final instance = Singleton._();}

当你需要使用的时候,只需要这样呼叫:

final singleton = Singleton.instance;

提醒: 要注意当你切换到不同的isolate时,不应该去更改这个Singleton内的值。

5.在你的class内Override 'toString()' 让你在debug的时候更方便

class Person {    const Person({        required this.name,        required this.height,        required this.weight,    });        final String name;    final double height;    final double weight;        @override    String toString() => 'name: $name, height: $height cm, weight $weight kg';}void main() {    const mike = Person(name: 'Mike', height: 188, weight: 80);    print(mike);    -> (name: Mike, height: 188cm, weight: 80kg)}

如果没有覆写toString(),当你print出来时就会得到

Instance of 'Person'

6.当在写注解时使用三个斜线(/)

当在写一个新的class或是function在写注解时,可以使用三个斜线,这样当其他开发者或是自己以后来看时,滑鼠只需要放到function上就可以直接看到注解,方便其他人开发跟理解。

class MathHelper {    /// 两数相加    static double plus(double x, double y) {        return x+y;    }}

http://img2.58codes.com/2024/20151194sAxE28ZunE.png

今天就先介绍到这里,如果有任何问题、错误或是希望我介绍的主题都可以留言告诉我,谢谢!


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章