flutter:函数声明、函数对象和函数调用

  1. 函数声明(Function Declaration)
  2. 函数对象(Function Object)
  3. 函数调用(Function Invocation)
  4. 三者关系总结
  5. 在 Flutter 里的真实场景

函数声明(Function Declaration)

定义函数本身,告诉 Dart 编译器“这里有一个函数”。

  • 它只是一个语法结构,类似于类的定义。
  • 不会执行,不会占用内存去运行。
// 这里的 sayHello 是 函数声明。
void sayHello() {
  print("Hello");
}

函数对象(Function Object)

在 Dart 里,函数可以像变量一样被当作对象传递、存储。

  • 当你写 sayHello(没有括号)时,你拿到的就是函数对象的 引用
  • 它的类型就是 Function 或更具体的 void Function()
// 这里的 sayHello 是 函数声明。
void sayHello() {
  print("Hello");
}

void main() {
  // 函数对象
  var f = sayHello;  
  // 这里 f 就是 函数对象,相当于指针/引用。
  print(f is Function); // true
}

函数调用(Function Invocation)

给函数加 (),表示执行函数。也就是调用函数对象,让它运行函数体里的代码。

// 这里的 sayHello 是 函数声明。
void sayHello() {
  print("Hello");
}
void main() {
  sayHello();   // 调用函数声明
  var f = sayHello; 
  f();          // 调用函数对象
}

三者关系总结

概念 代码表现 说明
函数声明 void sayHello(){} 定义函数,类似于类的定义
函数对象 var f = sayHello; 引用函数,赋值/传递/存储
函数调用 sayHello();f(); 执行函数体里的代码

在 Flutter 里的真实场景

import 'package:flutter/material.dart';
import 'package:get/get.dart';

class HomeController extends GetxController {
  var counter = 0.obs;

  void increment() => counter++;
}

class HomeBinding extends Bindings {
  @override
  void dependencies() {
    Get.put(HomeController()); 
  }
}

class HomePage extends GetView<HomeController> {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("GetView 示例")),
      body: Center(child: Obx(() => Text("点击次数: ${controller.counter}"))),
      floatingActionButton: FloatingActionButton(
        // 传递函数对象(点击时调用)
        onPressed: controller.increment,
        // 如果写 onPressed: controller.increment(),会在 build 时立刻执行,不是点击时才执行
        child: Icon(Icons.add),
      ),
    );
  }
}

void main() {
  runApp(
    GetMaterialApp(
      initialRoute: "/",
      getPages: [
        GetPage(
          name: "/",
          page: () => HomePage(),
          binding: HomeBinding(),
        ),
      ],
    ),
  );
}

×

喜欢就点赞,疼爱就打赏