概述
参考 : https://codelabs.flutter-io.cn/codelabs/from-java-to-dart-cn/index.html#0
Dart 是 Flutter 的主要开发语言 (前提 Java 开发者)
引入的知识
- 如何创建构造函数
- 用不同方法指定参数
- 如何正确地创建 getter 和 setter 方法
- Dart 如何处理可访问特性
- 如何使用 Dart 创建工厂模式
- Dart 中的函数式编程
- 有关 Dart 其他的一些核心概念
在线编辑工具:
https://dartpad.cn/
开始
定义 Bicycle 类
https://codelabs.flutter-io.cn/codelabs/from-java-to-dart-cn/index.html#1
class Bicycle {
int cadence;
int speed;
Int get speed => _speed;
int gear;
}
void main() {
}
新增构造函数
class Bicycle {
int cadence;
int speed;
int gear;
//Bicycle(this.cadence, this.speed, this.gear);
//与上面的等价
Bicycle(int cadence, int speed, int gear) {
this.cadence = cadence;
this.speed = speed;
this.gear = gear;
}
}
//验证
void main() {
var bike = new Bicycle(2, 0, 1);
print(bike.cadence);
}
优化输出信息
class Bicycle {
int cadence;
int speed;
int gear;
//Bicycle(this.cadence, this.speed, this.gear);
//与上面的等价
Bicycle(int cadence, int speed, int gear) {
this.cadence = cadence;
this.speed = speed;
this.gear = gear;
}
@override
String toString() => 'Bicycle: $speed mph';
}
//验证
void main() {
var bike = new Bicycle(2, 1, 1);
print(bike.toString());
}
只读变量
将 speed 变量 改造为 私有变量
class Bicycle {
int cadence;
//私有变量仅在库内部可见
int _speed = 10;
int gear;
//Bicycle(this.cadence, this.speed, this.gear);
//与上面的等价
Bicycle(int cadence, int gear) {
this.cadence = cadence;
this.gear = gear;
}
void applyBrake(int decrement) {
_speed -= decrement;
}
void speedUp(int increment) {
_speed += increment;
}
//getter 方法
int get speed => _speed;
@override
String toString() => 'Bicycle: $_speed mph';
}
//验证
void main() {
var bike = new Bicycle(2, 1);
print(bike.toString());
print(bike._speed);
bike._speed = 100;
print(bike._speed);
}