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

middle

Where are the layout files? Why doesn’t Flutter have layout files?

expert

Explain Stateful Widget Lifecycle in details

middle

How is InheritedWidget different from Provider ?

Bình luận

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

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