Pfeil. Alles, was Sie über Konstanten wissen müssen


Konstanten sind nicht nur eine seltsame Version von finalVariablen, die Sie in einem Traum mit all den damit verbundenen Fehlern verfolgen werden. Compile-timeKonstanten sind eine gute Möglichkeit, die Leistung Ihrer Anwendung zu verbessern, ohne dasselbe Objekt mehrmals zu erstellen, und sozusagen Objekte beim Kompilieren vorab zu erstellen.


const oder final?


, , . , , const final . .


void run() {
  const myConstNumber = 5;
  final myFinalNumber = 5;

  myConstNumber = 42; // 
  myFinalNumber = 42; // 
}

final, const , . , const .


class MyClass {
  final int myFinalField;
  const int myConstField; // 

  MyClass(this.myFinalField, this.myConstField);
}

, , final, const. , , (. ). ...



Dart . , "hello", , 3.14, , .


, .


void run() {
  const myList = [1, 2, 3];
  const myMap = {'one': 1};
  const mySet = {1, 2, 3};
}

: , if, spread , .


, const final , , . Dart , , . .



, , , . , .


void run() {
  final finalVariable = 123456;
  const constVariable = 123456;

  const notWorking = finalVariable; // 
  const working = constVariable;
}

, – , , , ...



Flutter const , , EdgeInsets, . - , .


const EdgeInsets.all(8), . , const , .

, const . : final .


class MyConstClass {
  final int field1;
  final List<String> field2;
  const MyConstClass(this.field1, this.field2);
}

void run() {
  //      
  const constVariable = 123456;
  const x = MyConstClass(constVariable, ['hello', 'there']);
}

, , const .


class MyWannabeConstClass {
  //  Future  const   
  final Future<int> field;
  // Dart  ,  ,  :
  const MyWannabeConstClass(this.field);
}

void run() {
  // Dart      const:
  const x = MyWannabeConstClass(Future.value(123)); // 
}

Dart , , , ""? , . const , . .


void run() {
  //  Future        
  final implicitNew = MyWannabeConstClass(Future.value(123));
  final explicitNew = new MyWannabeConstClass(Future.value(123));
}

const , , , Flutter .


, const final .


, new , const .


void run() {
  const implicitConst = MyConstClass(1);
  const explicitConst = const MyConstClass(1);
}

const , , , .


void run() {
  final regularVariable = const MyConstClass(1);
}

Fazit


Hoffentlich konnte dieser Leitfaden die Bedeutung von constKonstruktoren und im Allgemeinen Konstanten in Dart klären . Versuchen Sie, constes nach Möglichkeit zu verwenden, und Sie werden zeilenweise kleine Leistungsverbesserungen in Ihren Anwendungen vornehmen. Und Sie wissen, wie es mit kleinen Verbesserungen passiert - sie ergeben ein Gesamtergebnis.


All Articles