void main() {
var p = Person();
p.name = "Tom";
p.age = 22;
p.work(); //name is Tom,age is 22,he is worker
}
class Person {
String name;
int age;
//箭頭函數以及插值表達式
work() => print("name is \$name,age is \$age,he is worker");
//報錯不能重載
// work(String work){
//
// }
}
複製代碼
void main() {
var rect = Rect();
rect.width = 20;
rect.height = 10;
print(rect.area); //200
rect.area=300;
print(rect.width);//15
}
class Rect {
num width, height;
//計算屬性
num get area {
return width * height;
}
set area(value) {
width = value / 20;
}
//面積方法
getArea() => width * height;
}
複製代碼
void main(){
var p = Person("yxjie", 28, "your heart");
var p2 =Person.withAddress("你的肺");
}
class Person{;
String name;
int age;
final String address;//只能經過語法糖方式賦值
// Person(String name,int age){
// this.name=name;
// this.age=age;
// }
//與上面等價
Person(this.name,this.age,this.address);
//定義多個構造方法
Person.withAddress(this.address);
}
複製代碼
void main(){
var p = Person("Jerry", 16);
// p.name="hhah";//報錯
}
class Person{
final String name;
final int age;
const Person(this.name,this.age);
}
複製代碼
####工廠構造方法java
class AndroidUtil{
final String name;
//工廠構造方法 特色返回一個對象實列
factory AndroidUtil(String name){
return AndroidUtil._innerConstruct(name);
}
AndroidUtil._innerConstruct(this.name);
}
複製代碼
//初始化列表方式賦值
Person.withMap(map) : address = map["address"] {
this.name = map['name'];
this.age = map["age"];
}
複製代碼
####對象操做符bash
void main() {
var person;
person?.work(); //不會運行
var p;
p = "";
p = Person();
(p as Person).work();
if(p is Person){
p.work();
}
//級聯操做
var p1 = Person();
p1
..name = "jerry"
..age = 16;
}
class Person {
work() => print("work ...");
}
複製代碼
Dart中對象call方法相似於java中toString方法,區別在於Dart中call方法直接調用對象實列就行,java須要對象.toString()函數