×

Dart Function

A Dart function is a collective line of code that are targeted to perform a specialised task. Such lines of code (function) can be reused whenever we need to perform that specific task in a program. It is used to basically breakdown the large code into smaller modules. This approach increases the modularity of the code and makes the program way more readable and easier to debug.

We can call functions with the flexibility of running them with different values using the parameters and they also can return some value wherever the function is called in the program.

Advantages of Functions

Following are some advantages of the Dart function:

  • It enhances the modular approach for solving the problems
  • It increases the reusability of the code as well as program.
  • The code gets greatly optimized.
  • The debugging becomes a lot easier.
  • It makes development significantly easier and reduces the complexity as well.

How to Define a Function

A function definition refers to the body of the function that describes the task that function can perform. It includes the return type followed by name of the function and then parentheses which may or may not enclose the parameters of the function. A function contains a set of statements closed within curly brackets which is the function body.

The syntax of a function is as follows:

Syntax:

return_type func_name ( parameter_list ) :  

{ 

   // body of the function

   // This statement returns some value of the return type of the 

     function

   return value ;

} 
  1. Return Statement : - return value ;

return_type refers to the data types provided by Dart such as void, integer, double, string. This statement returns a value of that function. It is selected on the basis of whether a function returns any value or not, and if it returns then of what type.

For example, if the function is not supposed to return anything, then we use void as the return type and in that case the function body will not contain the return statement. While, if a function can return an integer value, then we integer as the return type and the function does contain a return statement.

  1. Function Name : - func_name( ) ;

func_name( ) refers to the name of the function by which it will be referred to in the program. It should be an appropriate and valid identifier. All the rules for a valid identifier apply here as well. A name defining the functionality of the function is appreciated.

  1. parameter_list : -

It refers to the list of the parameters which consist of variables with their data types separated by commas. These are necessary when a function is called.

Program

import 'dart:io';

int sum( int a, int b ) {

  int s ;

  s = a + b ;




  return s ;

}




void main( ) {

  print( ' Enter the value of a : ' ) ;

  int? x = int.parse( stdin.readLineSync( ) ! ) ;




  print( ' Enter the value of b : ' ) ;

  int? y = int.parse( stdin.readLineSync( ) ! ) ;




  int s = sum( x, y ) ;

  print( ' The sum of these two variables is ' ) ;

  print( s ) ;

}

Output

Enter the value of a :

5

Enter the value of b :

10

The sum of these two variables is

15

Calling a Function

A function defined outside the main( ) function is called or invoked inside the main( ) function as the execution of the program begins with main( ) only. A function is invoked by its name followed with the parameter list, if any. This statement is also referred as the call statement.

Whenever a function is called, the control of the program is transferred to the called function for the execution of all the defined statements and returns the resultant value to the calling function. The control then returns to the main( ) function after the execution of the called function is complete.

Syntax:

fun_name( < argument_list > ) ;  // When the function does not return any value

or 

variable = function_name( argument list ) ;  // When the function returns a value   

Example :

s = sum( 5, 10 ) ;

sum( 5, 10 ) ;

Passing Arguments to Function

A function is called according to the information written in the function prototype and is known as parameter (argument).The number of parameters passed as well as their data type must match with the number of parameters mentioned during the declaration of the function. Otherwise, an error will be generated. Parameter passing is not mandatory, which means it is not compulsory to mention the parameters during function declaration.

Following are the types of parameters :

Actual Parameters – These are the parameters that are passed to function definition.

Formal Parameters – These are the parameter that are passed to the function call.

Optional Parameters - These are the parameters that are not mandatory to be passed to the function, and are optional. Following are their types :

  • Optional Positional Parameter – Specified using the square brackets (‘[ ]’).
  • Optional Named Parameter – Specified using curly brackets (‘{ }’).
  • Optional parameter with default values – Parameters are assigned with some default values.

Program

// function 1 definition

void func1( var a, [ var b ] )

{

    print( " Value of a is $a " ) ;

    print( " Value of b is $b " ) ;

}




// function 2 definition

void func2( var a, { var b, var c } )

{

    print( " Value of a is $a " ) ;

    print( " Value of b is $b " ) ;

    print( " Value of c is $c " ) ;

}




// function 3 definition

void func3( int a, { int b : 12 } )

{

    print( " Value of a is $a " ) ;

    print( " Value of b is $b " ) ;

}

void main( )

{

    // Calling the function with optional parameter

    print( " Calling the function with optional parameters : " ) ;

    func1( 01 ) ;




    // Calling the function with Optional Named parameter

    print( " \n Calling the function with Optional Named parameters : ") ;

    func2( 01, c : 12 ) ;




    // Calling function with default valued parameter

    print( " \n Calling function with default valued parameters " ) ;

    func3( 01 ) ;

}

Output

Calling the function with optional parameter :

Value of a is 1

Value of b is null


Calling the function with Optional Named parameter :

Value of a is 1

Value of b is null

Value of c is 12



Calling function with default valued parameter

Value of a is 1

Value of b is 12

Let’s modify the program and try to understand the concept of parameters more efficiently,

// function 1 definition

void func1( var a, { var b, var c } )

{

    print( " Value of a is $a " ) ;

    print( " Value of b is $b " ) ;

    print( " Value of c is $c " ) ;

}

void main( )

{

    // Calling the function with optional parameter

    print( " Calling the function with optional parameters : " ) ;

    func1( b : 5, c : 6 ) ;

}

This code throws the compilation error.

Error : 1 positional argument(s) expected, but 0 found.

This is because variable a is a mandatory parameter and we did not pass any value to that parameter. Hence the error says, 1 positional argument expected.

Return a Value from Function

Whenever a function is called in the program, it returns some value. The return keyword is used to return a value. Although, the return statement is completely optional. But a function can have only one return statement.

The syntax is as follows.

Syntax:

return <expression/values> 

Example -

return result; 

Consider the following examples in Dart that explains the concept of functions:

  1. Check whether the number is prime or not.
import 'dart:io' ;

void main( )

{

  int i, flag = 0 ;

  print( ' Enter the number : ' ) ;

  int? n = int.parse( stdin.readLineSync( ) ! ) ;




  flag = prime( n ) ;

  if (n == 1) {

    print( " 1 is neither prime nor composite. " ) ;

  } else {

    if (flag == 0)

      print( " Number is a prime number. " ) ;

    else

      print( " Number is not a prime number. " ) ;

  }

}




int prime( int n )

{

  int flag = 0 ;

  for ( int i = 2; i <= n / 2; i++ )

  {

    if ( n % i == 0 )

   {

      flag = 1 ;

      break ;

    }

  }




  return flag ;

}

Output

Enter the number :

5

Number is a prime number.




Enter the number :

10

Number is not a prime number.
  1. Multiplication of two numbers
import 'dart:io';

void main( )

{

  print( ' Enter the value of a : ' ) ;

  int? a = int.parse( stdin.readLineSync( ) ! ) ;




  print( ' Enter the value of b : ' ) ;

  int? b = int.parse( stdin.readLineSync( ) ! ) ;




  mult( a, b ) ;

}




void mult( int a, int b )

{

  int m ;

  m = a * b ;




  print( ' \n Product of the two numbers is : ' ) ;

  print( m ) ;

}

Output

Enter the value of a :

5

Enter the value of b :

10

Product of the two numbers is :

50

Related Topics

Dart this Keyword

The ' this ' keyword, similar to that in Java and C#, refers to an object of the class using it. It points to the current object of the class,...

5 minutes read.

Unit Testing in Dart

Typing testing ensures that your app keeps working as you add more features or change existing functionality. Unit testing helps to confirm the behavior of a single function, method, or...

4 minutes read.

Soundness in Dart

What is soundness? Soundness ensures that the program never comes across any invalid state that may lead to abrupt termination of the program. As its name suggests it ensures perfect type...

4 minutes read.

Dart Isolates

Dart successfully supports asynchronous programming which runs our program without any hindrance. This asynchronous programming is used to achieve concurrency. Dart supports concurrent programming with features such as ‘ async-await...

9 minutes read.

Dart Inheritance

Inheritance is a promising concept of any programming language. It is a property by which a class inherits the property of another class. Moreover, the class deriving the properties of...

5 minutes read.

Dart Installation Guide

There are various ways of compiling and running an application created in Dart, either by compiling the Dart code to JavaScript using the Dart2js tool or by running on the...

3 minutes read.

Dart Runes and Graphemes

Runes and Graphemes data types in Dart Runes and Graphemes Runes are the special string of Unicode UTF-32 bits that represent the special syntax. Unicode defines a unique numeric value for each...

2 minutes read.

Dart Symbols

Symbols data type in Dart A symbol is an object that is the representation of an operator or identifier in Dart. These are compile-time constants.  They are used in APIs that refer...

1 minute read.

Dart Single-Page Application Architecture

In a single page application architecture, the source code for a single web page loads the entire application. The responsibility of building the user interface and requesting data from the...

2 minutes read.

Dart Variables

Variables are used to store the value of a particular data type referred to in the whole program by a name or identifier. They refer to a memory location as...

5 minutes read.

Dart HTML DOM

All web pages can be viewed as objects and exist within the browser window. We can access a web page using a web browser and it needs to be connected...

3 minutes read.

Dart Exception Handling

Exception Class – An exception is any runtime error that leads to abrupt termination of the program. It helps in addressing the error programmatically. It is aimed to be caught...

4 minutes read.

Dart Standard Input & Output

Standard Input in Dart (stdin): The standard input stream reads data both synchronously and asynchronously from the keyboard.  In Dart programming language, .readLineSync( ) function is used to accept input from the...

3 minutes read.

Dart - Control Flow Statements

The control flow statements are used to define the control on the flow of the program. Dart programs are executed in sequential order i.e., the order in which the programming...

1 minute read.

Dart Type inference

The task of interpreting the data types of fields, methods, local variables and most generic type arguments is handled by the static analyser. However, when not enough information is provided...

5 minutes read.

Dart If-else statement

In the previous section, we studied about if statements in detail. If – block is executed when the condition evaluates to true, else if the condition evaluates to false, then...

1 minute read.

Dart If statement

If statement is used to set the control on the lines of code. Using if statement, block of code is executed only if the expression in the statement returns true....

1 minute read.

Dart Types of Functions

Functions are the set of statements intended to perform a specific task. They accept some input from the user, perform the specified computation and generate the output. They are very...

4 minutes read.

Dart Maps

Map is an object-based data structure that associates keys and values that can be of any data type. Every key can occur only once, while the values can be used multiple...

5 minutes read.

Builder Classes in Dart

Before understanding builder classes, let us understand about Flutter that makes the best use of the builder classes. Flutter is actually not a programming language, it is a software development...

6 minutes read.