我正在我的 flutterfire 项目中准备一个类,我想使用一些不能进一步改变的方法,所以我想知道 Dart 中 static 关键字的概念?
最佳答案
“静态”意味着成员在类本身而不是在类的实例上可用。这就是它的全部含义,它没有用于任何其他用途。 static 修改成员。
静态方法 静态方法(类方法)不对实例进行操作,因此无权访问 this。但是,它们确实可以访问静态变量。
void main() {
print(Car.numberOfWheels); //here we use a static variable.
// print(Car.name); // this gives an error we can not access this property without creating an instance of Car class.
print(Car.startCar());//here we use a static method.
Car car = Car();
car.name = 'Honda';
print(car.name);
}
class Car{
static const numberOfWheels =4;
Car({this.name});
String name;
// Static method
static startCar(){
return 'Car is starting';
}
}
https://stackoverflow.com/questions/66594141/