Hàm (Function) trong Dart
🎯 Mục tiêu: Định nghĩa và sử dụng functions trong Dart.
💡 Cú pháp cơ bản
int add(int a, int b) {
return a + b;
}
void greet(String name) {
print("Hello, $name!");
}📝 Arrow Function (=>)
int add(int a, int b) => a + b;
void greet(String name) => print("Hello, $name!");🔧 Optional Parameters
Positional optional
String greet(String name, [String? title]) {
return title != null ? "$title $name" : name;
}
greet("Alice"); // "Alice"
greet("Alice", "Dr."); // "Dr. Alice"Named parameters
void createUser({
required String name,
int age = 0,
String? email,
}) {
print("Name: $name, Age: $age, Email: $email");
}
createUser(name: "Alice", age: 25);🎯 Default Values
int add(int a, [int b = 0, int c = 0]) {
return a + b + c;
}
void greet({String name = "Guest"}) {
print("Hello, $name!");
}📱 Trong Flutter
// Named params cho widgets
ElevatedButton(
onPressed: handleClick,
child: Text("Click"),
);
// Callback functions
void onItemTapped(int index) {
setState(() => _selectedIndex = index);
}✅ Checklist
- Dùng
=>cho single expression - Dùng
[]cho optional positional - Dùng
{}cho named parameters - Dùng
requiredcho required named params
Last updated on