Functions in Dart

Learn via video courses
Topics Covered

Overview

Functions are chunks of code in Dart that may be defined to accomplish certain tasks. They can accept arguments, process data, and, if desired, deliver a response. Dart allows for named, optional, and positional arguments, allowing for more flexible function invocations. Functions are first-class objects, which means they may be assigned to variables, used as arguments, and returned by other functions. This feature enables developers to write modular, reusable code, which improves code organization and readability. Functions are essential in Dart programming, allowing for the design of expressive and efficient applications.

Introduction

A Dart function is a collection of programs that work together to do a specified goal. It is used to divide big amounts of code into smaller modules that may be reused as needed. Functions make the program more readable and debuggable. It promotes the modular approach and code reusability. Assume we develop a basic calculator program in which we must conduct operations several times when the user inputs data. For each calculator operator, we may write a distinct function. We don’t have to create code for adding, subtracting, multiplying, and dividing over and again by utilizing functions. We can call the functions several times to use them multiple times.

The method allows you to run a code numerous times with varied values. A function can be called a parameter at any time and returns some value to the place where it was called.

The Dart function has a few advantages, which are listed below.

  • It improves the modular method of problem-solving.
  • It improves the program's reusability.
  • We can link the programs together.
  • It improves the code.
  • It facilitates debugging.
  • It simplifies development and reduces complexity.

Function Declaration and Syntax

Function declarations in Dart specify the structure and behavior of functions. Dart's function declaration syntax is as follows:

The following is a breakdown of the components:

  • returnType:
    The data type of the value returned by the function. If the function does not return any value, use void.
  • functionName:
    The function's name. Use a descriptive name that adheres to Dart naming guidelines.
  • parameter1Type, parameter2Type:
    The data types of the parameters that the function accepts are parameter1Type and parameter2Type. Parameters are optional in Dart and can be of any valid data type.
  • parameter1Name, parameter2Name:
    Within the function body, these names are used to refer to the appropriate parameters given when the function is called.
  • Function body:
    The code block enclosed by curly brackets that describes the function’s behavior. This is where the function’s logic is written.
  • return returnValue:
    An optional return statement that specifies the value that the function will return. The function's return type must match the returnType.

Examples:

  1. No-parameter function with no return value:

    Output:

  2. A parameterized function with a return value:

    Output:

  3. Optional arguments for the function:

    Output:

    Functions are first-class objects in Dart, which means they may be assigned to variables, supplied as arguments to other functions, and returned from functions, making Dart a versatile and powerful language for developing expressive and modular applications.

Function Invocation

Function invocation in Dart is the process of invoking a function to execute its code and, optionally, obtain the function’s return value if it returns one. To invoke a function, use its name followed by brackets() and any needed arguments within the brackets (if the function accepts parameters). In Dart, the syntax for calling a function is as follows:

  • functionName:
    The name of the function that will be called.
  • argument1, argument2:
    The values to be supplied to the function as arguments (if the function accepts parameters). The number and order of the arguments must match the parameter list of the function.

Examples:

  1. Invocation of a function with no arguments and no return value:

    Output:

  2. Invoking a function with arguments and a return value:

    Output:

  3. Invoking a function with optional arguments:

    Output:

    Dart supports function calls with various argument combinations, such as named arguments and default values for optional parameters. Understanding function invocation is essential for dealing with functions and writing modular and reusable Dart programs.

Parameters

Parameters are variables in Dart that are used to send data to functions or methods when they are called. A function's parameters are stated within the brackets (). In Dart, there are two sorts of parameters:

Optional Parameters

Optional parameters are the most common form of parameter. They are specified in the function declaration in the order in which they should be given when the function is called. Positional parameters are another name for them. Positional arguments are surrounded by square brackets [] and are optional, which means they can be left out when invoking the function.

Output:

Named Parameters

When invoking a function, named parameters are parameters that are identifiable by their names. They are surrounded by curly braces and preceded by their names, which are followed by a colon. Named arguments are optional, and they can be sent to the function in any order.

Output:

When invoking a function, named parameters are parameters that are identifiable by their names. They are surrounded by curly braces and preceded by their names, which are followed by a colon. Named arguments are optional, and they can be sent to the function in any order.

Functions as Objects

Functions are first-class objects in Dart, which means they may be treated exactly like any other data type, such as integers, strings, lists, and so on. Functions can be assigned to variables, used as parameters in other functions, returned from, and stored in data structures such as lists or maps. Because functions may be treated as objects, powerful and flexible programming paradigms can be created. A function can be sent as a parameter to another function. As an example:

Output:

Dart offers a wide range of programming methods like higher-order functions, closures, and callback patterns by treating functions as objects. Dart is a flexible language for numerous programming paradigms due to its flexibility, which enables clean and simple code.

Anonymous Functions

Most functions, such as main() and printElement(), are named. You may also write a nameless function known as an anonymous function, or a lambda or closure. You may attach an anonymous function to a variable to add or delete it from a collection, for example. An anonymous function resembles a named function in appearance, with zero or more arguments separated by commas and optional type annotations between parentheses. The following code block includes the function's body:

The example below creates an anonymous function with an untyped parameter, or item, and sends it to the map function. Each string in the list is converted to uppercase by the function, which is called for each item in the list. Each transformed string is then written out in the anonymous function supplied to forEach.

Output:

Use Functions to Split up Code

Functions are key tools in Dart for breaking down code into smaller, reusable parts. You may improve the organization, maintainability, and readability of your code by splitting difficult tasks down into smaller functions. In Dart, here’s how you utilize functions to divide up code:

  • Analyse Your Code for Reusable Tasks:
    Examine your code for tasks that are repeated or may be split from the primary logic. These tasks may be suitable for separating into different functions.
  • Define Functions:
    Use the returnType functionName(parameters) syntax to define functions. The returnType specifies the kind of value returned by the function (use void if the function returns nothing). The functionName is a descriptive name for the function and the variables that the function accepts as inputs are specified by the parameters.
  • Write Function Logic:
    Encapsulate the exact purpose that the function is supposed to execute inside each function.
  • Call Functions:
    In the proper context, call the functions, passing any needed parameters. Functions can be called numerous times from various portions of the code, which encourages code reuse.

Example:

Consider a program that computes the area of a rectangle and a circle. The code may be divided into two functions, one for the rectangle and one for the circle:

Output:

The code for calculating the area of a rectangle and a circle in this example is divided into two functions: calculateRectangleArea and calculateCircleArea. These routines take the necessary arguments and compute the area. These functions are called by the main function to compute and show the areas. You may improve code maintainability, remove redundancy, and make your codebase more modular by organizing code into smaller functions. This method makes code easier to read and alter, particularly as your project develops in complexity.

Conclusion

  • A Dart function is a collection of programs that work together to achieve a specified goal, dividing large amounts of code into smaller modules that can be reused as needed. It promotes modularity, and code reusability, and simplifies development.
  • Function declarations in Dart specify the structure and behavior of functions, with returnType, functionName, parameter1Type, parameter2Type, parameter names, function body, and return returnValue.
  • Function invocation in Dart involves invoking a function to execute its code and obtain its return value if it returns one.
  • Dart offers a wide range of programming methods, such as higher-order functions, closures, and callback patterns, making it a flexible language for numerous programming paradigms.
  • Functions as objects are first-class objects in Dart, allowing them to be assigned to variables, used as parameters in other functions, returned from, and stored in data structures like lists or maps.