Learn Dart · 4/12

Functions: Building Reusable Blocks

5 min read

Course: Dart

Topic: Functions: Building Reusable Blocks


👋 Introduction

Welcome to the DRY zone. No, we aren't talking about the weather; we are talking about the golden rule of programming: Don't Repeat Yourself.

Imagine you are writing a program to calculate the tax for a shopping cart. You write the math formula. Then, you need to calculate tax for a different user. You copy-paste the code. Then a third user. Copy-paste again. Suddenly, the government changes the tax rate. Now you have to hunt down every single place you pasted that code and change it. If you miss one? Bug city. 🐛

This leads to "Spaghetti Code"—a tangled mess that is impossible to maintain.

The Solution? Functions.
Functions allow you to encapsulate logic into a single "box" that you can call whenever you need it. If the logic changes, you change it in one place, and the whole app updates. Magic! ✨

Let's break down how Dart handles these building blocks.


1. Defining Functions and Return Types

The Definition

A function is a named block of code that performs a specific task. It can take input, process it, and send back a result.

The Anatomy

In Dart, functions look like this:

dart
ReturnType functionName(ParameterType parameterName) {
  // Body of the function
  return value; 
}

🏗️ Hands-on: Your First Function

Let's say we need to add two numbers.

dart
// Explicitly typing the return value as 'int'
int addNumbers(int a, int b) {
  return a + b;
}

void main() {
  int result = addNumbers(5, 10);
  print(result); // Output: 15
}

Key Concept: The void Keyword
Sometimes, a function doesn't need to return data to the caller; it just needs to do something (like print text or save a file). For this, we use void.

dart
void greetUser(String name) {
  print("Hello, $name! Welcome to Dart.");
  // No 'return' statement needed here
}

Industry Standard Tip: Always explicitly declare your return types (int, String, void). Dart allows you to omit them (dynamic typing), but writing them out makes your code self-documenting and safer. Your future self will thank you.


2. Positional and Named Parameters

The Problem: "Mystery Meat" Navigation

Look at this function call:
createUser("John", 25, true, false, "Admin");

What is 25? Age? ID? Shoe size? What is true? Is he active? Is he an admin? Is he allergic to peanuts?
This relies on Positional Parameters. You must pass arguments in the exact order they are defined. It works, but it's hard to read.

The Solution: Named Parameters

Named parameters allow you to label your arguments when calling the function. This is the Gold Standard in Flutter development (almost every Widget uses named parameters).

To define named parameters, wrap them in curly braces {}.

dart
// Definition
void createUser({required String name, required int age, bool isAdmin = false}) {
  print("User: $name, Age: $age, Admin: $isAdmin");
}

// Usage
void main() {
  // The order doesn't matter anymore!
  createUser(age: 30, name: "Alice", isAdmin: true);
  
  createUser(name: "Bob", age: 25); // isAdmin defaults to false
}

Concept: The required Keyword
Since Dart has Null Safety, if you define a named parameter like {String name}, Dart worries: "What if the user doesn't pass a name?"
You have two choices:

  1. Make it nullable (String? name).
  2. Force the user to provide it using required.

In 99% of industry code, if the data is essential, use required.


3. Optional and Default Parameters

The Problem

Sometimes you want a function to be flexible. Maybe you want to greet someone, but you don't always know their title (Mr./Ms.). Or maybe you want a default settings configuration without typing it every time.

The Solution: Optional Positional Parameters

Wrap parameters in square brackets [] to make them optional. They rely on position but don't have to be passed.

dart
String buildSandwich(String bread, [String? filling, String? sauce]) {
  return "Sandwich with $bread" + 
         (filling != null ? ", $filling" : "") + 
         (sauce != null ? " and $sauce" : "");
}

void main() {
  print(buildSandwich("Wheat")); 
  // Output: Sandwich with Wheat
  
  print(buildSandwich("White", "Cheese"));
  // Output: Sandwich with White, Cheese
}

Default Values

What if you want a parameter to be optional, but have a fallback value instead of null? You can assign a default value using =. This works for both named and positional parameters.

dart
// 'port' is optional, but defaults to 8080 if not provided
void connectToServer({String serverName = "localhost", int port = 8080}) {
  print("Connecting to $serverName on port $port...");
}

4. Arrow Functions (=>) and Anonymous Functions

The Problem: Verbosity

Programmers are lazy (in a good way). Writing a 3-line function just to return a simple calculation feels like too much work.

The Solution: Arrow Syntax (=>)

Also known as the "Fat Arrow" syntax. It’s a shorthand for { return expression; }.

Standard Way:

dart
int square(int number) {
  return number * number;
}

Arrow Way:

dart
int square(int number) => number * number;

Note: You can only use => if the function body is a single expression.

Anonymous Functions (Lambdas)

Sometimes you need a function for a one-time use, like defining what happens when a button is clicked or filtering a list. You don't need to give it a name.

These are heavily used in functional programming methods like .map(), .forEach(), or .where().

dart
void main() {
  List<String> fruits = ['Apple', 'Banana', 'Mango'];

  // This function inside forEach has no name!
  // It takes 'fruit' as an argument and prints it.
  fruits.forEach((fruit) {
    print("I love $fruit");
  });
  
  // Even shorter with Arrow syntax
  fruits.forEach((fruit) => print("I love $fruit"));
}

🧠 Interesting Fact

In Dart, functions are "First-Class Citizens."
This sounds like a political status, but it means functions can be:

  1. Assigned to variables.
  2. Passed as arguments to other functions.
  3. Returned from other functions.

This is the secret sauce behind Flutter's ability to pass onPressed: () { doSomething(); } into buttons!


📚 References & Extra Reading


Next up, we will dive into Control Flow. But first, try converting your last "Calculator" homework into a class with named parameters! 🚀

Challenge

You are tasked with creating a robust Dart function to process user data. This function, formatUserData, must be defined using modern Dart best practices for clarity and flexibility, including a mix of required, optional, and default parameters.

Requirements:

  1. Define a function named formatUserData that returns a String.
  2. The function must accept the following parameters:
    • An optional positional parameter role of type String?.
    • A required named parameter name of type String.
    • A required named parameter age of type int.
    • A named parameter city of type String with a default value of "Unknown".
  3. The function's body should construct and return a formatted string.
  4. The returned string must follow this exact format: User: [NAME], Age: [AGE], City: [CITY], Role: [ROLE]
    • [NAME], [AGE], and [CITY] should be replaced by the values of their respective parameters.
    • [ROLE] should be the value of the role parameter. If role is null, it should be replaced with the string "Guest".
  5. Implement the entire function body using a single return statement.

Expected result

Your submission should consist of a single Dart function named formatUserData.

The function signature must correctly declare all specified parameters in the correct order:

  • An optional positional parameter role that accepts a nullable String.
  • A block of named parameters {...} containing:
    • A required String parameter named name.
    • A required int parameter named age.
    • A String parameter named city with a default value of "Unknown".

The function body must contain a single return statement that produces a String. This string should correctly interpolate the parameter values into the specified format, properly handling the case where role is null by substituting it with "Guest".

dart

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.