Bỏ qua để đến nội dung

Biến (Variable) - var, final, const

🎯 Mục tiêu: Hiểu 3 cách khai báo biến trong Dart và khi nào dùng mỗi loại.


Dart có 3 keywords khai báo biến:

  • var: Biến có thể thay đổi
  • final: Hằng số runtime (gán 1 lần)
  • const: Hằng số compile-time
var mutable = "Can change";
final runtimeConst = DateTime.now();
const compileConst = 3.14159;

var count = 0;
count = 1; // OK
count = 2; // OK
var name = "Dart";
name = "Flutter"; // OK
// name = 123; // Error! Không thể đổi kiểu
String name = "Dart";
int age = 10;
double price = 99.99;
bool isActive = true;

final gán được 1 lần, giá trị xác định lúc runtime:

final name = "Alice";
final currentTime = DateTime.now(); // OK - runtime value
// name = "Bob"; // Error! Cannot reassign
final list = [1, 2, 3];
// list = [4, 5, 6]; // Error! Cannot reassign reference
list.add(4); // OK! Nội dung vẫn có thể thay đổi

const là hằng số biết trước lúc compile:

const pi = 3.14159;
const maxUsers = 100;
// const now = DateTime.now(); // Error! Not compile-time constant
const list = [1, 2, 3];
// list.add(4); // Error! Cannot modify const list

Keyword Mutable Thời điểm Use case
var ✅ Yes Runtime Biến thường
final ❌ No Runtime Gán 1 lần, giá trị runtime
const ❌ No Compile Hằng số, config
var a = 10;
a = 20; // OK
final b = DateTime.now();
// b = DateTime.now(); // Error
const c = 100;
// c = 200; // Error

late String description;
void initialize() {
description = "Initialized later";
}
// Với initialization
late final int value = computeExpensiveValue();

Bài tập: Chọn keyword phù hợp

void main() {
// TODO: Chọn var/final/const phù hợp
_____ pi = 3.14159;
_____ currentUser = getCurrentUser();
_____ counter = 0;
_____ maxRetries = 3;
_____ timestamp = DateTime.now();
}

Lời giải:

void main() {
const pi = 3.14159; // Compile-time constant
final currentUser = getCurrentUser(); // Runtime, set once
var counter = 0; // Will change
const maxRetries = 3; // Compile-time constant
final timestamp = DateTime.now(); // Runtime value
}

class MyWidget extends StatelessWidget {
// const cho immutable values
static const padding = 16.0;
static const backgroundColor = Colors.white;
// final cho widget properties
final String title;
final VoidCallback? onTap;
const MyWidget({
required this.title,
this.onTap,
});
@override
Widget build(BuildContext context) {
// var cho local mutable state
var isHovered = false;
return ...;
}
}

[!TIP] Ưu tiên theo thứ tự: const > final > var

  • Dùng const khi biết giá trị lúc compile
  • Dùng final khi gán 1 lần lúc runtime
  • Dùng var chỉ khi cần thay đổi

  • Phân biệt var, final, const
  • Hiểu const là compile-time, final là runtime
  • Sử dụng late cho lazy initialization
  • Ưu tiên immutability khi có thể

Tiếp theo: Null Safety