Search⌘ K
AI Features

Calling and Defining a Function

Explore how to define and call functions in Dart. Understand the components of a function, how to pass data in and out, use built-in methods, and write reusable logic for easier program maintenance.

As we write more complex programs, writing the same logic multiple times becomes tedious and prone to errors. A function is a block of code designed to perform a specific task. We give this block of code a name, allowing us to execute it whenever needed without rewriting the underlying logic.

Like mathematical functions, programming functions take an input, perform operations on that input, and return a resulting output. A function operates similarly to a machine in a factory. Raw materials enter the machine, the machine processes them, and a finished product comes out the other end.

Built-in functions and methods

Before we write custom functions, it helps to identify the functions we already use. We can divide functions into two broad categories based on how they attach to data: top-level functions and methods.

A top-level function exists independently in our code. The print statement is a built-in top-level function. We pass an argument to it, and it displays that argument in the console.

A method is a function attached to a specific object. We call a method directly on an object using a dot. Let us examine Dart's built-in indexOf method to see how this works. We call indexOf on a string to calculate the starting position of a specific substring. Dart measures positions using a zero-based index. The ...