概述

  1. Dart 中函数是对象,可以:赋值给变量,作为参数传递,从函数中返回(高阶函数).

代码示例

三种参数
匿名函数
箭头函数
void main() {
  // 1. 必传参数
  printUser("Alice", 20);

  // 2. 可选位置参数([])
  printAddress("Tokyo");
  printAddress("Tokyo", "Shibuya");

  // 3. 可选命名参数({})
  printOrder(item: "Coffee");
  printOrder(item: "Coffee", price: 18.5, count: 2);
}

// -----------------------------
// 1. 必传参数
// -----------------------------
void printUser(String name, int age) {
  print("User: $name, Age: $age");
}

// -----------------------------
// 2. 可选位置参数([])
//    - 可省略
//    - 按顺序填充
//    - 可设默认值
// -----------------------------
void printAddress(String city, [String district = "Unknown"]) {
  print("City: $city, District: $district");
}

// -----------------------------
// 3. 可选命名参数({})
//    - 可省略
//    - 通过名字传递
//    - 可设默认值
//    - 可以 required
// -----------------------------
void printOrder({
  required String item,
  double price = 10.0,
  int count = 1,
}) {
  print("Order: $item, Price: $price, Count: $count");
}
void main() {
  // 1. 匿名函数赋值给变量
  var greet = (String name) {
    print("Hello, $name");
  };
  greet("Alice");

  // 2. 匿名函数作为参数传递
  runTask(() {
    print("Task is running...");
  });

  // 3. 匿名函数用于列表操作
  var numbers = [1, 2, 3, 4];
  numbers.forEach((n) {
    print("Number: $n");
  });

  // 4. 匿名函数作为返回值(闭包)
  var add = createAdder(5);
  print(add(10)); // 输出 15
}

// ------------------------------
// 接收匿名函数作为参数
// ------------------------------
void runTask(Function action) {
  action();
}

// ------------------------------
// 返回匿名函数(闭包)
// ------------------------------
Function createAdder(int x) {
  return (int y) {
    return x + y;
  };
}
void main() {
  // 1. 最基本的箭头函数
  int square(int x) => x * x;
  print(square(5)); // 25

  // 2. 箭头函数赋值给变量
  var greet = (String name) => print("Hello, $name");
  greet("Alice");

  // 3. 箭头函数作为参数传递
  runTask(() => print("Task is running..."));

  // 4. 箭头函数用于列表操作
  var numbers = [1, 2, 3, 4];
  var doubled = numbers.map((n) => n * 2).toList();
  print(doubled); // [2, 4, 6, 8]

  // 5. 箭头函数返回值(闭包)
  var add = createAdder(10);
  print(add(5)); // 15
}

// ------------------------------
// 接收箭头函数作为参数
// ------------------------------
void runTask(Function action) => action();

// ------------------------------
// 返回箭头函数(闭包)
// ------------------------------
Function createAdder(int x) => (int y) => x + y;