Function Parameter in Dart

Parameter In Dart

The parameter is the process of passing values to the function. The values passed to the function must match the number of parameters defined. A function can have any number of positional parameters.

Optional Named Parameter

Optional Named parameters are optional parameters. But if they are marked as required, then the named parameters will be mandatory as the user is required to pass the value. Default values are required as parameters can’t be null. Curly braces {} are used to specify named parameters.

Syntax

void function_name(a, {optional_parameter1, optional_parameter2}) { } //Declaring function
function_name(optional_param:value,); //Calling function
void main(){
  Student('Shyam', roll:114, age:24);
}
void Student(var name, {var roll, var age}){
  print('Name = $name');
  print('Id= $roll');
  print('Age = $age');
}
Show Output

Optional positional parameter

Square [] brackets are used to specify positional parameters. By default, Optional positional parameters will be Null unless the value is passed.

Syntax

void function_name(param1, [optional_param_1, optional_param_2]) { }

Example

void main(){
   Cities('Kathmandu', 'Pokhara');
}

void Cities(String name1, String name2, [String? name3]){
  print('$name1 is capital city of Nepal.');
  print('$name2 is beautiful city of Nepal.');
  print('$name3 is the birth place of Gautam Budhdha.');
}
  
Show Output

Default parameter

If no value is provided then the default value is Null. The default value should be compiled time constant. In default values function can use ‘=’ to both named and optional parameters.

void main(){
  Student1("Shyam");
  Student2("Rounok");
  
}
//Named parameter
void Student1(var name, {var age = 25}){
  print('Name = $name');
  print('Age = $age');
}

//Optional parameter
void Student2(var name,{var age = 37}){
  print('Name = $name');
  print('Age = $age');
}
  
Show Output

Arrow Function

Dart supports a nice shorthand syntax for any function that has only one expression. Arrow functions implicitly return the result of the expression. => expression; is the same as {return expression;}. There is no need to (and you can’t) include the return keyword. This function is used to make your code short.

String takeFive(int number) => ‘$number minus five equals ${number - 5}’;

String studentName(String name) => '$name!';

void main() {
    print(studentName('Prabin'));
}

Callback Function

Here are some steps for callback function in dart.

  • step 1: Take function as a parameter.
  • step 2: Set data to function, the data which must be sent back from delegate class.
  • step 3: Pass function in parameters from calling class.

Here is complete code:


  callIt(Function callback) {
    var result = callback();
    return 'Result: $result';
  }