thumbnail

Functions in Dart

Published on 29 March 2020
Last Updated on 29 March 2020

What are Functions in Dart

In Dart programming language, everything is an object. Functions in Dart have an abject type Function and they can be assigned to variables and passed around other functions as parameters.

Function definition

Regular Functions in Dart are usually defined as follows:

retun_type function_name(parameters){
    function_body;
    return_statement;
}

Lambda Functions also known as arrow functions in Dart are usually defined as follows:

retun_type function_name => return_statement;

Program that demonstrates how to use Functions in Dart

// Program that demonstrates how to use Functions in Dart

// package meta is required to mark optional named parameters as required
import 'package:meta/meta.dart';

// this function adds two numbers
// this function does not make use of type definitions for function parameters
int addTwoNumbers(a, b) {
  // check if a and b are not null
  if (a != null && b != null) {
    return a + b;
  }
  return 0;
}

// function that adds three numbers
// makes use of type definitions while accepting parameters
int addThreeNumbers(int a, int b, int c) {
  if (a != null && b != null && c != null) {
    return a + b + c;
  }
  return 0;
}

// defining a simple function using the arrow syntax
// equivalent to: bool isEven(a){ return a % 2 == 0; }
bool isEven(a) => a % 2 == 0;

// functions with named parameters where last name has a default value of ''
void sayHello({String firstName = '', String lastName = ''}) {
  print('Hello ${firstName} ${lastName}!');
}

// functions with named parameters
// both the parameters are marked as required
// none of the named parameters have a default value
// if no value is specified while calling this function then analyzer will report a warning
// also note that, you must import package:meta to use @required annotation
void sayGoodBye({@required String firstName, @required String lastName}) {
  print('Good bye ${firstName} ${lastName}!');
}

// function with named parameters where default value of all parameters is defined
void speak({String word = 'abc'}) {
  print('abc');
}

// function that demonstrates the use of optional parameters
void optionalParametersTest(String requiredParameter,
    [String optionalParameter = 'xyz']) {
  print(
      'requiredParameter:${requiredParameter}, optionalParameter:${optionalParameter}');
}

// main function
void main(List<String> args) {
  print('calling addTwoNumbers');
  print(addTwoNumbers(1, 2));

  print('calling addThreeNumbers');
  print(addThreeNumbers(1, 2, 3));

  print('calling isEven');
  print(isEven(1));

  print('calling sayHello with no last name specified');
  sayHello(firstName: 'lorem');

  print('calling sayHello with all parameters specified');
  sayHello(firstName: 'lorem', lastName: 'ipsum');

  print('calling sayGoodBye with all parameters specified');
  sayGoodBye(firstName: 'john', lastName: 'doe');

  print('calling speak with no parameter values specified');
  speak();

  print(
      'calling optionalParametersTest with no optional parameter value specified');
  optionalParametersTest('abc');

  print(
      'calling optionalParametersTest with optional parameter value specified');
  optionalParametersTest('abc', 'lmnop');
}

Above program produces following output:

calling addTwoNumbers
3
calling addThreeNumbers
6
calling isEven
false
calling sayHello with no last name specified
Hello lorem !
calling sayHello with all parameters specified
Hello lorem ipsum!
calling sayGoodBye with all parameters specified
Good bye john doe!
calling speak with no parameter values specified
abc
calling optionalParametersTest with no optional parameter value specified
requiredParameter:abc, optionalParameter:xyz
calling optionalParametersTest with optional parameter value specified
requiredParameter:abc, optionalParameter:lmnop

Function return type

Each function in Dart has a return type, if no return type as specified for the function then the function has the return type void.

Every function in Dart must return a value, if a function does not have a return statement then function returns void.

main() function in Dart

main() function in Dart is the entry point to the app. Every app must have a main function.

main function can be defined as follows:

void main(List<String> args) {}

or

void main() {}

Make use of optional args parameter to define and parse command line argument. It is also recommended to make use of args library if you are interested in doing so.

Parameter types in Dart

There are various ways to define function parameters in Dart. In above program we have demonstrated all of them.

Function parameters with no type definition

In above program, following function does not make use of type definitions while defining function parameters.

// this function adds two numbers
// this function does not make use of type definitions for function parameters
int addTwoNumbers(a, b) {
  // check if a and b are not null
  if (a != null && b != null) {
    return a + b;
  }
  return 0;
}

Above function is called as follows:

print(addTwoNumbers(1, 2));

Because above function does not make use of type definitions in its function parameters, it is important to make sure that function is properly defined to handle other types as well.

Function parameters with a type definition

Following function makes use of function parameters while accepting parameters.

// function that adds three numbers
// makes use of type definitions while accepting parameters
int addThreeNumbers(int a, int b, int c) {
  if (a != null && b != null && c != null) {
    return a + b + c;
  }
  return 0;
}

Above function can be called by using following code:

print(addThreeNumbers(1, 2, 3));

Arrow functions also known as lambda functions

Code given below defines a simple function using the arrow syntax

bool isEven(a) => a % 2 == 0;

Above code is equivalent to:

bool isEven(a){
    return a % 2 == 0; 
}

Use lambda functions if you are defining a simple function that immediately returns a value.

Functions with optional named parameters

Given below is an example of a function that makes use of named parameters.

Please note that function definition given below, also specifies default value for parameters.

void sayHello({String firstName = '', String lastName = ''}) {
  print('Hello ${firstName} ${lastName}!');
}

Above function can be called as follows:

sayHello(firstName: 'lorem');
sayHello(firstName: 'lorem', lastName: 'ipsum');

As shown in above example, named parameters are optional they can be excluded from function calls if a default value is already specified.

Use @required annotation to make optional named parameters required in function calls.

void sayGoodBye({@required String firstName, @required String lastName}) {
  print('Good bye ${firstName} ${lastName}!');
}

Dart analysis shows a information message in your analysis messages if required argument is not specified in function call.

Function with optional positional parameters

Refer to code given below that makes use of function that demonstrates the use of optional parameters.

void optionalParametersTest(String requiredParameter,
    [String optionalParameter = 'xyz']) {
  print(
      'requiredParameter:${requiredParameter}, optionalParameter:${optionalParameter}');
}

Above code can be called via following function call:

// does not define optional parameter
optionalParametersTest('abc');

// defines optional parameter
optionalParametersTest('abc', 'lmnop');