
الثوابت ليست مجرد نسخة غريبة من final
المتغيرات التي ستطاردك في المنام مع كل الأخطاء المرتبطة بها. Compile-time
الثوابت هي طريقة جيدة لتحسين أداء التطبيق الخاص بك ، دون إنشاء نفس الكائن عدة مرات ، إذا جاز التعبير ، "إنشاء مسبق" لكائنات في وقت الترجمة.
أم نهائي؟
, , . , , 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 {
final Future<int> field;
const MyWannabeConstClass(this.field);
}
void run() {
const x = MyWannabeConstClass(Future.value(123));
}
Dart , , , ""? , . const
, . .
void run() {
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);
}
استنتاج
نأمل أن يكون هذا الدليل قادرًا على توضيح معنى const
المنشئين ، وبشكل عام ، الثوابت في Dart. حاول استخدامه const
حيثما أمكن ، وستقوم بإجراء تحسينات صغيرة على الأداء في تطبيقاتك سطرًا تلو الآخر. وأنت تعرف كيف يحدث ذلك مع التحسينات الصغيرة - فهي تعطي نتيجة شاملة.