×

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 lists data type

The most important data type in any programming language is an ordered list of elements, an array. Dart lists resemble JavaScript array lists. Example,               var...

7 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 Object-Oriented Concepts

Dart is a programming language that supports object-oriented programming. It is focused on the objects that are real-world entities and supports all the concepts of OOPS, such as objects, classes,...

4 minutes read.

Rust vs Dart

Rust is a system-level programming language that stands next to C ++ in terms of syntax, but offers greater speed and memory security. Dart, on the other hand, is an...

2 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.

Dart Sets

Sets data type in Dart A set is an unordered collection of items that are unique. Dart infers that sets tale strings as values. Example, var languages = { ‘Dart’ , ‘Flutter’, ‘Python’,...

3 minutes read.

Dart URIs

The Uri class supports encoding and decoding of strings with the help of functions to be used in URIs ( which may also be known as URLs ). These functions...

6 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 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 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 Classes

Dart is an object – oriented programming language that supports all the object-oriented programming concepts such as classes, objects, inheritance, data abstraction and data encapsulation. A class can be defined as...

8 minutes read.

Dart Basic Program

Dart provides various convenient platforms to code and compile the program in Dart language. Some of them are: 1. Using IDE = Visual Studio code is a text editor with IDE....

3 minutes read.

Abstract Classes in Dart

Abstract classes in Dart are those classes that only contain abstract methods  (methods that do not contain any implementation). These classes are specifically designed for the purpose of inheritance. We...

4 minutes read.

Dart Miscellaneous types

Some Other Data types in Dart Apart from the data types studied so far, we have three other data types also which are as follows: NeverDynamicVoid Let us understand each one in detail, Never...

3 minutes read.

Dart Recursion

Recursion is one of the most important and interesting concepts in any programming language. It can be defined as a process in which a function calls itself directly or indirectly....

5 minutes read.

Assert in DART

In any programming language, resolving error is the most unwanted and tedious task. At times it becomes very difficult to find the error in the large code. Dart offers an...

3 minutes read.

Dart Static Members

Static Members in Dart Static members are the members of the class declared using the 'static' keyword. the static members have the following characteristics :  All the objects of the class having...

3 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.

Dart Common Collection Methods

Most of the programming languages have arrays as a way to list items together. However, Dart has a collection of data structures similar to array. These are supported by the...

3 minutes read.

Dart Anonymous Function

Dart functions are the user defined functions that are designed to perform specific task. The use case of the functions is that they can be directly called any number of...

3 minutes read.