Dart Lesson 9 – Functions | Dataplexa

Functions in Dart

In this lesson, you will learn about functions in Dart. Functions allow you to group code into reusable blocks that perform a specific task.

Functions are a core building block of clean, scalable, and maintainable applications. Every real-world Dart project relies heavily on well-structured functions.


Why Functions Are Important

Without functions, programs become repetitive, hard to read, and difficult to maintain.

Functions help you:

  • Reuse code instead of repeating logic
  • Organize complex programs into smaller parts
  • Improve readability and debugging
  • Build scalable applications

Basic Function Structure

A basic Dart function has:

  • A return type
  • A function name
  • Optional parameters
  • A function body

Example: Calculate total price of items.

int calculateTotal(int price, int quantity) {
  return price * quantity;
}

void main() {
  int total = calculateTotal(50, 3);
  print("Total Price: $total");
}

This function takes inputs, processes data, and returns a result.


Functions Without Return Value

Functions that do not return a value use the void keyword.

Example: Log user activity.

void logActivity(String user) {
  print("User logged in: $user");
}

void main() {
  logActivity("Alice");
}

Such functions are commonly used for logging, printing, or notifications.


Functions With Optional Parameters

Dart allows optional parameters using square brackets [].

Example: Apply discount if provided.

double finalAmount(double amount, [double discount = 0]) {
  return amount - discount;
}

void main() {
  print(finalAmount(100));
  print(finalAmount(100, 15));
}

Optional parameters make functions flexible and reusable.


Named Parameters

Named parameters improve clarity and reduce errors.

Example: Process an order.

double processOrder({required double price, required int quantity}) {
  return price * quantity;
}

void main() {
  double total = processOrder(price: 75, quantity: 4);
  print(total);
}

Named parameters are widely used in real-world Dart and Flutter projects.


Arrow Functions (Short Syntax)

For simple logic, Dart supports arrow syntax.

Example: Calculate tax.

double calculateTax(double amount) => amount * 0.18;

void main() {
  print(calculateTax(200));
}

Arrow functions make code concise and readable.


Functions Using Lists

Functions often process collections such as lists.

Example: Calculate average score.

double averageScore(List scores) {
  int sum = 0;
  for (var score in scores) {
    sum += score;
  }
  return sum / scores.length;
}

void main() {
  print(averageScore([80, 90, 85, 95]));
}

This pattern is common in analytics and reporting systems.


Functions Calling Other Functions

Functions can call other functions to break complex logic into steps.

Example: Order processing pipeline.

double calculateSubtotal(double price, int quantity) {
  return price * quantity;
}

double addTax(double amount) {
  return amount * 1.18;
}

void main() {
  double subtotal = calculateSubtotal(100, 2);
  double finalTotal = addTax(subtotal);
  print(finalTotal);
}

This improves readability and maintainability.


Best Practices for Functions

  • Keep functions short and focused
  • Use meaningful function names
  • Avoid doing too many things in one function
  • Prefer named parameters for clarity

📝 Practice Exercises


Exercise 1

Write a function that calculates the square of a number.

Exercise 2

Create a function that returns the highest number from a list.

Exercise 3

Create a function that prints a welcome message for a user.


✅ Practice Answers


Answer 1

int square(int n) {
  return n * n;
}

Answer 2

int maxValue(List values) {
  int max = values[0];
  for (var v in values) {
    if (v > max) max = v;
  }
  return max;
}

Answer 3

void welcomeUser(String name) {
  print("Welcome, $name!");
}

What’s Next?

In the next lesson, you will learn about null safety in Dart.

Null safety is one of Dart’s most powerful features and is critical for writing reliable, crash-free applications.