Skip to Content
Dart📘 Ngôn ngữ DartBiến (Variable) - var, final, const

Biến trong Dart - 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.


💡 Khái niệm

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 - Biến có thể thay đổi

var count = 0; count = 1; // OK count = 2; // OK var name = "Dart"; name = "Flutter"; // OK // name = 123; // Error! Không thể đổi kiểu

Khai báo kiểu tường minh

String name = "Dart"; int age = 10; double price = 99.99; bool isActive = true;

🔒 final - Hằng số Runtime

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 với collections

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 - Hằng số Compile-time

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 collections - Immutable hoàn toàn

const list = [1, 2, 3]; // list.add(4); // Error! Cannot modify const list

📊 So sánh

KeywordMutableThời điểmUse case
var✅ YesRuntimeBiến thường
final❌ NoRuntimeGán 1 lần, giá trị runtime
const❌ NoCompileHằng số, config
var a = 10; a = 20; // ✅ OK final b = DateTime.now(); // b = DateTime.now(); // ❌ Error const c = 100; // c = 200; // ❌ Error

🔧 late - Khởi tạo muộn

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

🛠️ Thực hành

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 }

📱 Trong Flutter

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

⚠️ Lưu ý quan trọng

[!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

✅ Checklist

  • 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

Last updated on