Basics of Functions in Dart
 

Definition

A function in Dart is a block of code that performs a specific task. It's a reusable piece of code that can be called from other parts of your program.

Advantages of Using Functions

  • Code Reusability: Write once, use multiple times.
  • Modularity: Break down complex problems into simpler pieces.
  • Maintainability: Easier to update and manage code.
  • Readability: Makes the program easier to understand.

Use Cases

  • Performing calculations
  • Handling repetitive tasks
  • Managing data processing
  • Interacting with user input

Syntax

returnType functionName(parameters) {
  // function body   // return statement }
  • returnType: Specifies the type of value returned by the function. Use void if there is no return value.
  • functionName: The name of the function.
  • parameters: Optional. Values you can pass into the function.

Example Programs

Example 1: Simple Function

 

void greet() {
  print('Hello, World!');
}

void main() {
  greet(); // Calling the function }

Example 2: Function with Parameters

 

int add(int a, int b) {
  return a + b;
}

void main() {
  int sum = add(5, 3);
  print('Sum: $sum');
}

Example 3: Function with Optional Parameters

 

void printInfo(String name, [int? age]) {
  print('Name: $name');
  if (age != null) {
    print('Age: $age');
  }
}

void main() {
  printInfo('Alice');
  printInfo('Bob', 25);
}

Example 4: Arrow Functions

 

int multiply(int a, int b) => a * b;

void main() {
  print('Product: ${multiply(4, 5)}');
}

Conclusion

Functions are a fundamental part of Dart programming, enabling you to write clean and efficient code. With the ability to pass parameters and return values, functions provide flexibility and power in building applications.