基本操作:
// ??: 如果 b 等于 null,那么 a 为 c,如果 b 不等于 null,那么 a 为 b
var b = null;
var c = 2;
var a = b ?? c;
//关于sound null safety,参考:https://dart.dev/null-safety
//表示变量可能具有值为null,只需添加?
int? emptyNumber = null;
//操作符
// ?.
int y = 3;
int p = a?.y;
//匿名函数
var num = (int n) {
return n;
}
函数 自定义参数
//可选的位置参数 在[]中包装一组函数参数将它们标记为可选的位置参数:
String getInfos1(String name, [int? age]) {
if (age != null) return '姓名:$name---年龄:$age';
return '姓名:$name---年龄:保密';
}
//定义函数时,使用{param1,param2,...}指定命名参数:
String getInfos2(String name, {int? age}) {
return '姓名:$name---年龄:$age';
}
类
class Fruit {
String name; ////这个不加下划线的是一个共有的方法
double _price; //私有:可以使用 _ 把一个属性或者方法定义成私有(需在不同文件中
//构造函数中使用thie.argument赋值
Fruit(this.name, this._price);
//命名构造函数(可多个),使用命名构造函数来为类实现多个构造函数或提供extra clarity
Fruit.pome(String name, double price)
: this.name = name,
this._price = price;
Fruit.drupe(String name, double price)
: this.name = name,
this._price = price;
//get、set方法
get getPrice {
return this._price;
}
set setPrice(double price) => this._price = price;
//私有函数
void _run() {
print('此处为一个私有的函数');
}
//公有函数,执行私有函数
execrun() {
this._run();
}
}
类的调用
import 'lib/Fruit.dart';
void main() {
//默认构造函数
Fruit apple = new Fruit('apple', 8);
//命名构造函数
Fruit pear = new Fruit.pome('pear', 8);
Fruit? empty = null;
// ?.:使用 ?. 而不是 . 来避免当最左边的操作数为null时出现异常:
print(apple?.name); //此处会提示用 . 替换 ?. 因为不为null
print(empty?.name);
//set和get使用
print(pear.getPrice);
pear.setPrice = 10.0;
print(pear.getPrice);
//..级联符号:
//级联 ( .., ?..) 允许您对同一对象进行一系列操作。除了函数调用之外,您还可以访问同一对象上的字段。
//这通常可以为您节省创建临时变量的步骤,并允许您编写更流畅的代码。
pear
..name = 'watermelon'
..setPrice = 11.0;
//如果级联操作的对象可以为空,那么在第一个操作中使用一个空的级联(?..)。保证不对该空对象尝试任何级联操作。
empty
?..name = 'orange'
..setPrice = 8;
//执行公有函数
pear.execrun();
// extends继承
appple apple2 = new appple('apple', 8.0, 1.0);
apple2.printInfo();
}
类的基础时,“初始化列表”功能 :surper()
class appple extends Fruit {
double? weight;
//:super()——给父类默认构造函数传参
appple(String name, double price, double weight) : super(name, price) {
this.weight = weight;
}
//: super.xxx()——给父类命名构造函数传参
appple.pome(String name, double price, double weight)
: super.pome(name, price) {
this.weight = weight;
}
}
Comments | NOTHING