Skip to content

Latest commit

 

History

History
78 lines (57 loc) · 2.51 KB

ex3-3.md

File metadata and controls

78 lines (57 loc) · 2.51 KB

3.3 Using optional parameters

Example Code: Custom Delay using a Future

The printGreetingNamed() function takes two optional named parameters: personName and clientId. The default value for personName is "Stranger" and the default value for clientId is 999.

The first time the printGreetingNamed() function is called, no arguments are passed. The default values for personName and clientId are used.

The second time the printGreetingNamed() function is called, the argument personName is passed with the value "Rich". The default value for clientId is used.

The third time the printGreetingNamed() function is called, the arguments personName and clientId are passed with the values "Mary" and 001, respectively.

The printGreetingNamed() function checks if the value of the personName parameter contains the string "Stranger". If it does, the function prints the message "Employee: $clientId Stranger danger". If it does not, the function prints the message "Employee: $clientId $personName".

void main() {
  printGreetingNamed();
  printGreetingNamed(personName: "Rich");
  printGreetingNamed(personName: "Mary", clientId: 001);
}

void printGreetingNamed({String personName = 'Stranger', 
                         int clientId = 999}){
  if (personName.contains('Stranger')) {
    print('Employee: $clientId Stranger danger ');
  } else {
    print('Employee: $clientId $personName ');
  }
}

Example Output:

Employee: 999 Stranger danger
Employee: 999 Rich
Employee: 001 Mary

Example Code: Positional Parameters

The printGreetingPositional() function takes two positional parameters: personName and personSurname. The parameter personSurname is optional.

The first time the printGreetingPositional() function is called, the argument personName is passed with the value "Rich". The argument personSurname is not passed.

The second time the printGreetingPositional() function is called, the arguments personName and personSurname are passed with the values "Rich" and "Rose", respectively.

The printGreetingPositional() function prints the value of the personName parameter. If the value of the personSurname parameter is not null, the function prints the value of the personSurname parameter.

void main() { 
  printGreetingPositional("Rich");
  printGreetingPositional("Rich", "Rose");
}

void printGreetingPositional(String personName, [String? personSurname]){
  print(personName);
  if (personSurname != null){
    print(personSurname);
  }
}

Example Output:

Rich
Rich Rose