Calling and Defining a Function
Explore the fundamentals of defining and calling functions in Dart, including using built-in functions, creating custom functions with parameters and return types, and using arrow notation for concise code. Understand how functions help organize code into reusable and testable blocks for cleaner programming.
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 ...