var person = Person();
class Person{
String name;
int age;
void work(){
print("Name is $name,Age is $age,He is working...");
}
}
var person = Person();
person.age = 12;
person.name = "tom";
print(person.age);
person.work();
class Rectangle{
num width,height;
num get area => width * height;
}
var rect = Rectangle();
rect.height = 20;
rect.width = 10;
print(rect.area);//200
class Boy{
String name;
int age;
Boy(String name, int age){
this.name = name;
this.age = age;
print("Name is $name,Age is $age");
}
void work(){
print("Name is $name,Age is $age,He is working...");
}
}
若存在final属性:
class Boy{
String name;
int age;
inal String gender;
Boy(String name, int age,this.gender){
this.name = name;
this.age = age;
print("Name is $name,Age is $age");
}
void work(){
print("Name is $name,Age is $age,He is working...");
}
}
此时属性赋值在构造函数之前执行
构造方法语法糖:
Boy(this.name,this.age,this.gender);
同理属性赋值在构造函数之前执行
命名构造方法:
由于构造方法无法重载,要想给部分属性赋值时,可以采用赋值构造方法
class Boy{
String name;
int age;
inal String gender;
Boy(String name, int age,this.gender){
this.name = name;
this.age = age;
print("Name is $name,Age is $age");
}
Boy.withGender(this.gender);
void work(){
print("Name is $name,Age is $age,He is working...");
}
}
var boy = Boy.withGender("男");
boy.work();
常量构造方法:
class Dog{
final String name;
final int age;
const Dog(this.name,this.age);
}
工厂构造方法:
class Factory{
String message;
factory Factory(String message){
//message为dart时,实例化,否则返回空
if(message == "dart"){
return Factory.internal(message);
}else{
return null;
}
}
Factory.internal(this.message);
}
var factory = Factory("Java");
print(factory == null);//true
用于解决构造方法传入集合时,final变量的赋值问题
class Girle{
String name;
int age;
final String gender;
Girle.withMap(Map map) : gender = map["gender"]{
this.name = map["name"];
this.age = map["age"];
}
void work(){
print("Name is $name,Age is $age,Gender is $gender,She is working...");
}
}
var map = {"name":"tom","age":12,"gender":"女"};
var girle = Girle.withMap(map);
girle.work();
class Page{
static const int maxPage = 10;
static int currentPage = 1;
static void up(){
currentPage++;
print("currentPage = $currentPage");
}
static void down(){
currentPage--;
print("currentPage = $currentPage");
}
}
Page.up();//currentPage = 2
Page.down();//currentPage = 1
条件成员访问:?.
相当于在执行之前进行判空操作,如果为null则不再执行
var person;
person?.age = 12;
此时如果不适用?.则会crash
类型转换:as
person = "";
person = Person();
(person as Person).age = 12;
是否指定类型:"is & is! "用于判断对象的class
if(person is Person){
person.age = 12;
}
级联操作
person..name = "小李"
..age = 26
..work();
如果类实现了call()方法,则该类的对象化可以作为方法使用
class Animal{
String call(name,age)=>"Name is $name, age is $age";
}
var animal = Animal();
print(animal("小猫",1));//Name is 小猫, age is 1