Câu hỏi phỏng vấn Flutter
Câu hỏi

Differentiate between required and optional parameters in Dart

Câu trả lời

In Dart, parameters can be classified as either required or optional. Here's the difference between the two:

Required Parameters

  • Required parameters must be provided when calling a function or constructor.
  • They are defined without any special syntax, as the default behavior in Dart.
  • If a required parameter is missing, the code will not compile[1][2].

Example:

dart Copy
void printDetails(String name, int age) {
  print('Name: $name, Age: $age');
}

Calling the function requires providing both name and age:

dart Copy
printDetails('John', 25);

Optional Parameters

Optional parameters can be further divided into two types: optional positional parameters and optional named parameters.

Optional Positional Parameters

  • Enclosed in square brackets [][3].
  • Can have a default value specified using =[3].
  • If no default value is provided, the parameter's type must be nullable (int? instead of int)[3].

Example:

dart Copy
String say(String from, String msg, [String? device]) {
  var result = '$from says $msg';
  if (device != null) {
    result = '$result with a $device';
  }
  return result;
}

Calling the function with...

middle

middle

Gợi ý câu hỏi phỏng vấn

senior

What are Global Keys?

senior

How to compare two dates that are constructed differently in Dart?

entry

When to use main Axis Alignment and cross Axis Alignment?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào