为什么我们应该在dart中使用static关键字来代替abstract?

问题描述 投票:0回答:2

我正在我的 flutterfire 项目中准备一个类,我想使用一些无法进一步更改的方法,以便我想知道 Dart 中 static 关键字的概念?

flutter class dart static static-methods
2个回答
10
投票

“静态”意味着成员在类本身而不是类的实例上可用。这就是它的全部含义,并且不用于其他任何用途。静态修改成员

静态方法 静态方法(类方法)不对实例进行操作,因此无权访问该实例。然而,他们确实可以访问静态变量。

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';
  }
  
}

4
投票

Dart 中的

static
关键字用于声明只属于类而不属于实例的变量或方法,这意味着该类只有该变量或方法以及那些静态变量(类变量)或静态方法的一份副本(类方法)不能被类创建的实例使用。

例如,如果我们声明一个类:

class Foo {

    static String staticVariable = "Class variable";
    final String instanceVariable = "Instance variable";

    static void staticMethod(){
        print('This is static method');
    }

    void instanceMethod(){
        print('instance method');
    }
}

这里要记住的是静态变量只创建一次,并且类创建的每个实例都有不同的实例变量。因此,您不能从类实例中调用静态变量。 以下代码有效:

Foo.staticVariable; 
Foo().instanceVariable;
Foo.staticMethod();
Foo().instanceMethod();

但这会报错:

Foo().staticVariable;
Foo.instanceVariable;
Foo().staticMethod;
Foo.instanceMethod

静态变量和方法的使用

当您具有与类相关的常量值或通用值时,可以使用静态变量。

您可以在这里阅读更多内容。

© www.soinside.com 2019 - 2024. All rights reserved.