ZetCode

Dart 箭头函数

最后修改日期:2025 年 6 月 4 日

在 Dart 中,箭头函数为编写函数表达式提供了一种简洁的语法。它们也被称为 lambda 函数或匿名函数。

箭头函数使用 `=>` 语法定义一个执行单个表达式并返回其结果的函数。它们对于简短的函数和回调特别有用。

基本箭头函数语法

最简单的箭头函数接受参数并返回一个表达式。 `=>` 语法同时替换了花括号和 return 语句。

main.dart
void main() {
  // Traditional function
  int add(int a, int b) {
    return a + b;
  }
  
  // Arrow function equivalent
  int addArrow(int a, int b) => a + b;
  
  print(add(5, 3));      // 8
  print(addArrow(5, 3)); // 8
}

两个函数执行相同的加法操作。箭头版本更简洁。请注意,箭头函数只能包含一个表达式。

$ dart main.dart
8
8

带集合的箭头函数

箭头函数通常与 map 和 where 等集合方法一起使用。

main.dart
void main() {
  var numbers = [1, 2, 3, 4, 5];
  
  // Using arrow function with map
  var squares = numbers.map((n) => n * n).toList();
  print(squares); // [1, 4, 9, 16, 25]
  
  // Using arrow function with where
  var evens = numbers.where((n) => n % 2 == 0).toList();
  print(evens);   // [2, 4]
}

map 方法转换每个元素,而 where 方法过滤元素。箭头函数使这些操作简洁且易于阅读。

$ dart main.dart
[1, 4, 9, 16, 25]
[2, 4]

箭头函数作为回调

箭头函数非常适合用作事件处理程序和计时器的回调函数。

main.dart
void main() {
  // Timer with traditional callback
  Timer(Duration(seconds: 1), () {
    print('Timer finished!');
  });
  
  // Timer with arrow function callback
  Timer(Duration(seconds: 2), () => print('Arrow timer finished!'));
  
  // Simulating async operation
  Future.delayed(Duration(seconds: 1), () => 'Hello')
    .then((value) => print(value));
}

所有这三个示例都使用了回调函数。箭头版本更紧凑,同时保持清晰。Future.delayed 示例链接了箭头函数。

$ dart main.dart
Timer finished!
Hello
Arrow timer finished!

带命名参数的箭头函数

箭头函数可以与命名参数一起使用,从而提供灵活性。

main.dart
void main() {
  // Function with named parameters
  String greet({required String name, String title = 'Mr.'}) =>
      'Hello, $title $name!';
  
  print(greet(name: 'Alice', title: 'Ms.')); // Hello, Ms. Alice!
  print(greet(name: 'Bob'));                 // Hello, Mr. Bob!
  
  // Function with optional positional parameters
  String join(List<String> parts, [String separator = ' ']) =>
      parts.join(separator);
  
  print(join(['one', 'two', 'three']));       // one two three
  print(join(['one', 'two', 'three'], '-')); // one-two-three
}

两个示例都展示了带有不同参数类型的箭头函数。第一个使用了带有默认值的命名参数,而第二个使用了可选的位置参数。

$ dart main.dart
Hello, Ms. Alice!
Hello, Mr. Bob!
one two three
one-two-three

类方法中的箭头函数

箭头语法可用于简洁地定义类方法。

main.dart
class Point {
  final double x;
  final double y;
  
  Point(this.x, this.y);
  
  // Arrow function method
  double distanceTo(Point other) => 
      sqrt(pow(x - other.x, 2) + pow(y - other.y, 2));
  
  // Getter with arrow syntax
  String get description => 'Point($x, $y)';
}

void main() {
  var p1 = Point(0, 0);
  var p2 = Point(3, 4);
  
  print(p1.description);          // Point(0, 0)
  print(p2.description);          // Point(3, 4)
  print(p1.distanceTo(p2));       // 5.0
}

Point 类将箭头语法用于方法和 getter。这使得类定义更加紧凑,同时保持其可读性。

$ dart main.dart
Point(0, 0)
Point(3, 4)
5.0

最佳实践

来源

Dart 函数文档

本教程涵盖了 Dart 的箭头函数,并提供了实际示例来演示其语法和常见用法模式。

作者

我的名字是 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。至今,我已撰写了 1400 多篇文章和 8 本电子书。我在教授编程方面拥有十多年的经验。

列出 所有 Dart 教程