Flutter学习5 - Dart 方法类型

1、Dart 方法介绍

  • 方法的构成:返回值 + 方法名 + 参数
dart 复制代码
int sum1(int a, int b) {
  return a + b;
}
  • 返回值类型可缺省
dart 复制代码
sum2(int a, int b) {
  return a + b;
}
  • 参数类型可缺省
dart 复制代码
sum3(a, b) {
  return a + b;
}
  • 可通过 { } 设置可选参数;并为可选参数设置默认值
dart 复制代码
int sum4(int a, int b, {bool? isPrint = false}) {
  var result = a + b;
  if (isPrint ?? false) {
    print("计算结果:" + result);
  }
  return result;
}

void main() {
  sum4(1, 2, isPrint: true); //计算结果:3
}

2、常见方法

(1)入口方法

dart 复制代码
void main() {
  
}

(2)实例方法

  • 类中的方法
dart 复制代码
class Calculate {
  //实例方法
  int reduce(int a, int b, {bool isPrint = false}) {
    var result = a - b;
    if (isPrint) {
      print("结果:$result");
    }
    return result;
  }
}


void main() {
  Calculate calculate = Calculate();
  calculate.reduce(6, 4, isPrint: true); //结果:2
}

(3)私有方法

  • 私有方法:方法名前面添加下划线_
  • 作用域:当前的文件

main1.dart

dart 复制代码
void main() {
  Student student = Student();
  student.study(); //学习
  student._sleep(); //睡觉
  _add(1, 9); //add 结果:10
}

class Student {
  study() {
    print("学习");
  }

  //私有方法
  _sleep() {
    print("睡觉");
  }
}

//私有方法
_add(a, b) {
  print("add 结果:${a + b}");
}

main2.dart

dart 复制代码
void main() {
  _objectType();
  Student student = Student();
  student.study();
  student._sleep(); //报错
  _add(3, 4); //报错
}

(4)匿名方法

  • 匿名方法:没有名字的方法,有时也被称为 lambda 表达式 或 closure 闭包
dart 复制代码
void main() {
  _foo();
}

//匿名方法
_foo() {
  var list = ["私有方法", "匿名方法"];
  // void forEach(void action(E element))
  // 其中 void action(E element) 就是一个匿名方法
  // 类比 Kotlin 中将方法作为参数传递
  list.forEach((element) {
    print("${list.indexOf(element)}: $element");
    //0: 私有方法
    // 1: 匿名方法
  });
}
dart 复制代码
void main() {
  _reduce(3, 4, (c) {
    print("3 - 4 = $c"); //3 - 4 = -1
  });
}

// 匿名方法 void action(int c)
// 类比 Kotlin 中将方法作为参数传递
_reduce(int a, int b, void action(int c)) {
  action(a - b);
}

当不需要使用参数时,可以用 _ 隐藏,如下

dart 复制代码
void main() {
  _reduce(3, 4, (_) {
    print("3 - 4 = ?"); 
  });
}

_reduce(int a, int b, void action(int c)) {
  action(a - b);
}

(5)静态方法

  • 通过 "类名.静态方法" 的方式调用
dart 复制代码
void main() {
  Student.learning();
}

class Student {
  //静态方法
  static learning() {
    print("学生们在学习"); //学生们在学习
  }
}
相关推荐
瓜子三百克4 小时前
七、性能优化
flutter·性能优化
恋猫de小郭12 小时前
Flutter Widget Preview 功能已合并到 master,提前在体验毛坯的预览支持
android·flutter·ios
小蜜蜂嗡嗡18 小时前
Android Studio flutter项目运行、打包时间太长
android·flutter·android studio
瓜子三百克1 天前
十、高级概念
flutter
帅次1 天前
Objective-C面向对象编程:类、对象、方法详解(保姆级教程)
flutter·macos·ios·objective-c·iphone·swift·safari
小蜜蜂嗡嗡1 天前
flutter flutter_vlc_player播放视频设置循环播放失效、初始化后获取不到视频宽高
flutter
孤鸿玉2 天前
[Flutter小技巧] Row中widget高度自适应的几种方法
flutter
bawomingtian1232 天前
FlutterView 源码解析
flutter
Zender Han2 天前
Flutter 进阶:实现带圆角的 CircularProgressIndicator
flutter