Dart Tutorial

Dart Tutorial Single-Page Application Architecture Dart Features Dart Installation Guide Dart Basic Program Dart Syntax Dart Keywords Dart Variables Dart Comments Dart Standard Input Output Dart Important Concepts

Data Types

Built-in Data Types Numbers Strings Booleans Lists Sets Maps Runes and Graphemes Symbols Enumerations Constants Queues

Other data types

Objects Future and stream Iterable Miscellaneous types

OPERATORS

Precedence and associativity Arithmetic operators Equality and Relational operators Type Test Operators Assignment Operators Logical Operators Bitwise and Shift Operators Miscellaneous operators

Control Flow Statements

Introduction If statement If-else statement If-else-if statement Loops Switch and case Dart Break And Continue Assert In Dart

FUNCTIONS

Dart function Types of Functions Anonymous function main( ) function Lexical scope and closure Recursion Common Collection Methods

Object Oriented Concepts

Dart Object-Oriented Concepts Dart Classes Dart Constructors Dart This Keyword Dart Super Keyword Static Members Method Overriding Dart Interfaces Inheritance Dart Abstract Classes Dart Builder Classes Dart Callable Classes

Dart Type System

Dart Type System Dart Soundness Dart Type Inference

MISCELLANEOUS

Dart Isolates Dart Typedef Dart Metadata Dart Packages Dart Generics Dart Generators Dart Concurrency Dart Unit Testing Dart Html Dom Dart URIs Dart Extends, With and Implements Keywords Dart Optional Parameters Rust Vs Dart C++ vs Dart Golang Vs Dart Dart Basics Exception Handling

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