百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分类 > 正文

每个flutter开发人员都要知道的16个dart技巧

ztj100 2024-12-25 16:50 19 浏览 0 评论

本文分享我在flutter编程中的重要技巧,学会了您的代码风格将得到很大提高。

1. 你知道吗,Dart 支持字符串乘法。

下面的例子如何用字符串乘法打印圣诞树

void main() {
  for (var i = 1; i <= 5; i++) {
    print('' * i);
  }
}
// Output:
// 
// 
// 
// 
// 

是不是很酷?

你可以用它来检查在 Text widget中文本的长度是否合适。

Text('You have pushed the button this many times:' * 5)

2. 需要同时执行多个Future? 使用 Future.wait.

Consider this mock API class that tells us the latest numbers of COVID cases:

// Mock API class
class CovidAPI {
  Future<int> getCases() => Future.value(1000);
  Future<int> getRecovered() => Future.value(100);
  Future<int> getDeaths() => Future.value(10);
}

要同时执行这些future, 使用 Future.wait。参数需要 「futures」 的list并且会返回一个 「future」「list」:

final api = CovidAPI();
final values =await Future.wait([
    api.getCases(),
    api.getRecovered(),
    api.getDeaths(),
]);
print(values); // [1000, 100, 10]

当Future是「独立的」并且不需要「顺序」执行时,这样做起来就很理想。

3. 可以在Dart的class中实现一个 “call”方法,这样我们就可以像调用方法一样调用类。

下面是一个 PasswordValidator class:

class PasswordValidator {
  bool call(String password) {
    return password.length > 10;
  }
}

我们定义了一个call 方法, 再定义一个类的实例就可以像使用函数一样使用它:

final validator = PasswordValidator();
// can use it like this:
validator('test');
validator('test1234');
// no need to use it like this:
validator.call('not-so-frozen-arctic');

4. 需要调用回调方法,但前提是回调方法不为空?使用 "?.call()" 语法。

在下面的列子中我们定义了一个widget,并且要在事件触发时调用onDragCompleted 回调:

class CustomDraggableextends StatelessWidget {
  const CustomDraggable({Key key, this.onDragCompleted}) : super(key: key);
final VoidCallback? onDragCompleted;


  void _dragComplete() {
    // TODO: Implement me
  }
  @override
  Widget build(BuildContext context) {/*...*/}
}

为了调用回调函数,我们可能要写如下的代码:

  void _dragComplete() {
    if (onDragCompleted != null) {
      onDragCompleted();
    }
  }

但是我们可以使用如下的简单语法 (使用 ?.):

  Future<void> _dragComplete()async {
    onDragCompleted?.call();
  }

5. 使用匿名函数和函数作为参数

在Dart中, 函数是一等公民,并且能够作为其他函数的参数。

下面演示了定义一个匿名函数,并且赋值给 sayHi 变量:

void main() {
  final sayHi = (name) => 'Hi, $name';
  welcome(sayHi, 'Andrea');
}


void welcome(String Function(String) greet, String name) {
  print(greet(name));
  print('Welcome to this course');
}

将 sayHi 作为变量传给 welcome 方法的greet参数。

String Function(String) 是 一个函数「类型」 ,带有 String 参数 并且返回 String类型。 因为上面的匿名函数具有相同的 「signature」, 所以能够直接作为参数传递。


在list的 map, where, reduce 等操作时,这样的代码风格很常见。

举个计算数的平方的例子:

int square(int value) {
  // just a simple example
  // could be a complex function with a lot of code
  return value * value;
}

计算出数组的所有平方:

const values = [1, 2, 3];


values.map(square).toList();

这里使用 square 作为参数,因为square的 signature是符合map 操作期望的。所以我们可以不使用下面的匿名函数:

values.map((value) => square(value)).toList();

6. 可以将 collection-if 和 spreads 与列表、集合和map一起使用

Collection-if and spreads 在我们写代码时非常有用。

这些其实也可以和map一起使用。

看下面的例子:

const addRatings = true;
const restaurant = {
  'name' : 'Pizza Mario',
  'cuisine': 'Italian',
  if (addRatings) ...{
    'avgRating': 4.3,
    'numRatings': 5,
  }
};

我们定义了一个 restaurant 的map, 并且只有当 addRatings 是 true的时候才会添加 avgRating and numRatings 。 因为超过了一个key-value,所以需要使用 spread 操作符 (...)。

7. 如何以 null-safe的方法遍历整个map? 使用.entries:

看下面的一个例子:

const timeSpent = <String, double>{
  'Blogging': 10.5,
  'YouTube': 30.5,
  'Courses': 75.2,
};

下面是循环遍历key-value:

for (var entry in timeSpent.entries) {
  // do something with keys and values
  print('${entry.key}: ${entry.value}');
}

8. 使用命名构造函数 和 初始化列表使API更简洁.

比如我们要定义一个温度的类。

需要让我们的类支持「两个」摄氏和华氏两种命名构造函数:

class Temperature {
  Temperature.celsius(this.celsius);
  Temperature.fahrenheit(double fahrenheit)
    : celsius = (fahrenheit - 32) / 1.8;
  double celsius;
}

该类只需要一个变量来表示温度,并使用初始化列表将华氏温度转换为摄氏温度。

我们在使用时就可以像下面这样:

final temp1 = Temperature.celsius(30);
final temp2 = Temperature.fahrenheit(90);

9. Getters and setters

在上面的 Temperature 类中, celsius 用来表示温度。

但是有些用户可能喜欢华氏温度。

我们可以很容易通过getters and setters实现, 定义 computed 变量(学过vue的是不是感觉很熟悉). 继续看下面的例子:

class Temperature {
  Temperature.celsius(this.celsius);
  Temperature.fahrenheit(double fahrenheit)
    : celsius = (fahrenheit - 32) / 1.8;
  double celsius;
  double get fahrenheit
    => celsius * 1.8 + 32;
  set fahrenheit(double fahrenheit)
    => celsius = (fahrenheit - 32) / 1.8;
}

这下我们使用华氏温度或者摄氏温度就很容易了:

final temp1 = Temperature.celsius(30);
print(temp1.fahrenheit);
final temp2 = Temperature.fahrenheit(90);
temp2.celsius = 28;

提示: 使用命名构造函数、getter 和 setter 来改进类的设计。

10. 未使用的参数使用下划线表示

举一个常见的例子 ListView.builder:

class MyListView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemBuilder: (context, index) => ListTile(
        title: Text('all the same'),
      ),
      itemCount: 10,
    );
  }
}

上面的例子中我们没有使用itemBuilder的的参数 (context, index) 。因此我们可以使用下划线代替。

ListView.builder(
  itemBuilder: (_, __) => ListTile(
    title: Text('all the same'),
  ),
  itemCount: 10,
)

注意*: 这两个参数是不同的 (_ 和 __) ,它们是「单独的标识符。」*

11. 一个类只需要被初始化一次 (单例模式)? 使用带有私有构造函数的静态实例变量。

The most important property of a singleton is that there can only be 「one instance」 of it in your entire program. This is useful to model things like a file system.

// file_system.dart
class FileSystem {
  FileSystem._();
  static final instance = FileSystem._();
}

要在 Dart 中创建单例,您可以声明一个命名构造函数并使用_语法将其设为私有。

然后再定一个final类型的类静态实例。

从此,只能通过instance变量访问这个类。

// some_other_file.dart
final fs = FileSystem.instance;
// do something with fs

注意:如果不小心,单例可能会导致很多问题。在使用它们之前,请确保您了解它们的缺点。

12. 想要集合中的每一项都是唯一的? 使用Set而不是 List。

Dart中最常见的集合是 List.

list可以有重复的项, 有些时候我们想要元素是唯一的:

const citiesList = [
  'London',
  'Paris',
  'Rome',
  'London',
];

这时候我们就需要使用 Set (注意我们使用了 final):

// set is final, compiles
final citiesSet = {
  'London',
  'Paris',
  'Rome',
  'London', // Two elements in a set literal shouldn't be equal
};

上面的代码将产生警告,因为 London 包含了两个. 如果把set定义为 const ,代码将产生错误,并且不能编译成功:

// set is const, doesn't compile
const citiesSet = {
  'London',
  'Paris',
  'Rome',
  'London', // Two elements in a constant set literal can't be equal
};

我们使用set时,我们可以使用 union, difference, and intersectio等API

citiesSet.union({'Delhi', 'Moscow'});
citiesSet.difference({'London', 'Madrid'});
citiesSet.intersection({'London', 'Berlin'});

13. 怎么使用 try, on, catch, rethrow, finally

当我们使用基于Future的API时,try 和 catch 是非常有用的。

看看下面的例子:

Future<void> printWeather() async {
  try {
    final api = WeatherApiClient();
    final weather = await api.getWeather('London');
    print(weather);
  } on SocketException catch (_) {
    print('Could not fetch data. Check your connection.');
  } on WeatherApiException catch (e) {
    print(e.message);
  } catch (e, st) {
    print('Error: $e\nStack trace: $st');
    rethrow;
  } finally {
    print('Done');
  }
}

有以下几点需要主要:

  • 可以添加多个on 来捕获不同类型的异常。
  • 最后可以添加一个 catch 来捕获上面没有处理到的异常.
  • 使用rethrow语句将当前异常抛出调用堆栈,「同时保留堆栈追踪。」
  • 使用finally在Future完成后运行一些代码,无论它是成功还是失败。

使用Future相关的API时,一定要确保异常处理

14. Future的一些常用构造函数

Future中有一些方便的构造函数:Future.delayed,Future.value和Future.error。

我们可以使用Future.delayed 制造一定的延迟。第二个参数是一个(可选的)匿名函数,可以用它来完成一个值或抛出一个错误:

await Future.delayed(Duration(seconds: 2), () => 'Latte');

有时我们可以创建一个 Future 并立即返回,这在测试mock数据时非常有用:

await Future.value('Cappuccino');
await Future.error(Exception('Out of milk'));

我们可以用Future.value一个值来表示成功完成,或者Future.error表示错误。

15. 常见的 Stream 构造函数

Stream 类也带有一些方便的构造函数。以下是最常见的:

Stream.fromIterable([1, 2, 3]);
Stream.value(10);
Stream.empty();
Stream.error(Exception('something went wrong'));
Stream.fromFuture(Future.delayed(Duration(seconds: 1), () => 42));
Stream.periodic(Duration(seconds: 1), (index) => index);
  • 使用 Stream.fromIterable 从list创建Stream。
  • 使用 Stream.value 从一个单一值创建。
  • 使用 Stream.empty 创建一个空的stream。
  • 使用 Stream.error 包含错误值的stram。
  • 使用 Stream.fromFuture 创建一个只包含一个值的stream,并且该值将在未来完成时可用。
  • 使用 Stream.periodic 创建周期性的事件流。

16. Sync and Async Generators

我们可以定义一个 「synchronous」 generator(同步生成器) 函数的返回类型定义为 Iterable:

Iterable<int> count(int n) sync* {
  for (var i = 1; i <= n; i++) {
     yield i;
  }
}

这里使用了 sync* 语法. 在函数内部,我们可以yield多个值. 这些值将在函数完成时作为一个 Iterable 返回.


另外, 一个「asynchronous」 generator 需要使用 Stream作为返回值

Stream<int> countStream(int n)async* {
  for (var i = 1; i <= n; i++) {
     yield i;
  }
}

这里使用 async* 语法. 在函数内部,我们可以 yield 多个返回值。

「asynchronous」 generator中我们也可以使用Future相关的函数:

Stream<int> countStream(int n)async* {
  for (var i = 1; i <= n; i++) {
    // dummy delay - this could be a network request
    await Future.delayed(Duration(seconds: 1));
    yield i;
  }
}

最后

希望大家喜欢我提供的这写小技巧,快来使用它们来改进 Flutter 应用程序中的代码。大家可以留言告诉我,你们最喜欢哪个小技巧!!

相关推荐

sharding-jdbc实现`分库分表`与`读写分离`

一、前言本文将基于以下环境整合...

三分钟了解mysql中主键、外键、非空、唯一、默认约束是什么

在数据库中,数据表是数据库中最重要、最基本的操作对象,是数据存储的基本单位。数据表被定义为列的集合,数据在表中是按照行和列的格式来存储的。每一行代表一条唯一的记录,每一列代表记录中的一个域。...

MySQL8行级锁_mysql如何加行级锁

MySQL8行级锁版本:8.0.34基本概念...

mysql使用小技巧_mysql使用入门

1、MySQL中有许多很实用的函数,好好利用它们可以省去很多时间:group_concat()将取到的值用逗号连接,可以这么用:selectgroup_concat(distinctid)fr...

MySQL/MariaDB中如何支持全部的Unicode?

永远不要在MySQL中使用utf8,并且始终使用utf8mb4。utf8mb4介绍MySQL/MariaDB中,utf8字符集并不是对Unicode的真正实现,即不是真正的UTF-8编码,因...

聊聊 MySQL Server 可执行注释,你懂了吗?

前言MySQLServer当前支持如下3种注释风格:...

MySQL系列-源码编译安装(v5.7.34)

一、系统环境要求...

MySQL的锁就锁住我啦!与腾讯大佬的技术交谈,是我小看它了

对酒当歌,人生几何!朝朝暮暮,唯有己脱。苦苦寻觅找工作之间,殊不知今日之事乃我心之痛,难道是我不配拥有工作嘛。自面试后他所谓的等待都过去一段时日,可惜在下京东上的小金库都要见低啦。每每想到不由心中一...

MySQL字符问题_mysql中字符串的位置

中文写入乱码问题:我输入的中文编码是urf8的,建的库是urf8的,但是插入mysql总是乱码,一堆"???????????????????????"我用的是ibatis,终于找到原因了,我是这么解决...

深圳尚学堂:mysql基本sql语句大全(三)

数据开发-经典1.按姓氏笔画排序:Select*FromTableNameOrderByCustomerNameCollateChinese_PRC_Stroke_ci_as//从少...

MySQL进行行级锁的?一会next-key锁,一会间隙锁,一会记录锁?

大家好,是不是很多人都对MySQL加行级锁的规则搞的迷迷糊糊,一会是next-key锁,一会是间隙锁,一会又是记录锁。坦白说,确实还挺复杂的,但是好在我找点了点规律,也知道如何如何用命令分析加...

一文讲清怎么利用Python Django实现Excel数据表的导入导出功能

摘要:Python作为一门简单易学且功能强大的编程语言,广受程序员、数据分析师和AI工程师的青睐。本文系统讲解了如何使用Python的Django框架结合openpyxl库实现Excel...

用DataX实现两个MySQL实例间的数据同步

DataXDataX使用Java实现。如果可以实现数据库实例之间准实时的...

MySQL数据库知识_mysql数据库基础知识

MySQL是一种关系型数据库管理系统;那废话不多说,直接上自己以前学习整理文档:查看数据库命令:(1).查看存储过程状态:showprocedurestatus;(2).显示系统变量:show...

如何为MySQL中的JSON字段设置索引

背景MySQL在2015年中发布的5.7.8版本中首次引入了JSON数据类型。自此,它成了一种逃离严格列定义的方式,可以存储各种形状和大小的JSON文档,例如审计日志、配置信息、第三方数据包、用户自定...

取消回复欢迎 发表评论: