Trong Dart/Flutter, có sự phân biệt rõ ràng giữa các tham số bắt buộc và tùy chọn. Hãy phân tích chi tiết:
// Tham số bắt buộc thông thường
void example1(String name, int age) {
print('Name: $name, Age: $age');
}
// Tham số bắt buộc với từ khóa required trong named parameters
void example2({
required String name,
required int age,
}) {
print('Name: $name, Age: $age');
}
a) Optional Positional Parameters:
void example3(String name, [int? age, String? address]) {
print('Name: $name, Age: $age, Address: $address');
}
b) Optional Named Parameters:
void example4({String? name, int? age}) {
print('Name: $name, Age: $age');
}
void example5({
String name = 'Anonymous',
int age = 0,
}) {
print('Name: $name, Age: $age');
}
void main() {
// Gọi hàm với tham số bắt buộc
example1('John', 25);
// Gọi hàm với named required parameters
example2(name: 'John', age: 25);
// Gọi hàm với optional positional parameters
example3('John'); // Chỉ truyền tham số bắt buộc
example3('John', 25); // Truyền thêm age
example3('John', 25, 'New York'); // Truyền đầy đủ
// Gọi hàm với optional named parameters
example4(); // Không truyền tham số nào
example4(name: 'John'); // Chỉ truyền name
example4(name: 'John', age: 25); // Truyền đầy đủ
// Gọi hàm với default parameters
example5(); // Sử dụng giá trị mặc định
example5(name: 'John'); // Ghi đè giá trị mặc định của name
}
Trong Widget Flutter:
class CustomWidget extends StatelessWidget {
// Required parameters
final String title;
// Optional parameters
final Color? backgroundColor;
final double fontSize;
const CustomWidget({
required this.title, // Bắt buộc
this.backgroundColor, // Tùy chọn
this.fontSize = 14.0, // Tùy chọn với giá trị mặc định
});
@override
Widget build(BuildContext context) {
return Container(
color: backgroundColor,
child: Text(
title,
style: TextStyle(fontSize: fontSize),
),
);
}
}
Việc phân biệt và sử dụng đúng loại tham số sẽ giúp code trở nên: