OneBite.Dev - Coding blog in a bite size

Call A Function With Parameter In Dart

Code snippet for how to Call A Function With Parameter In Dart with sample and detail explanation

In this article, we’ll delve into how to call a function with a parameter in Dart, a key concept that is important for writing efficient and effective code. Understanding how to correctly use parameters within functions can allow for more dynamic coding.

Code snippet: Calling a function with a parameter in Dart

Here’s a simple example to start:

void main() {
  greet('James');
}

void greet(String name) {
  print('Hello, $name!');
}

In this Dart programming language code snippet, we defined a function greet() that has one parameter of type String and then we called this function from the main() function with the argument 'James'.

Code Explanation for: Calling a function with a parameter in Dart

Let’s break down the code we’ve written:

  1. The main function is where the execution of the Dart program starts. In the main function, we call the function greet() with a string value ‘James’.
void main() {
  greet('James');
}
  1. After the greet() function is called, execution moves to the body of the greet() function. Here, we have defined a function named greet() which is designed to print a greeting message. The greet() function has one parameter called name of type String.
void greet(String name) {
  print('Hello, $name!');
}
  1. This name parameter will hold the value passed to the function when it is called. Inside the greet() function, we use string interpolation (the $ symbol) to include the name variable directly within the string. The print() function then prints ‘Hello, James!’ to the console.

This simple example shows how to use a function with a parameter in Dart, making your code reusable and modular. Function parameters are often utilized in the Dart programming language to allow values to be passed into functions, which enhances the dynamics and maintainability of the code.

dart