Declare A Function With Single Parameter In Dart
Code snippet for how to Declare A Function With Single Parameter In Dart with sample and detail explanation
Dart, a general-purpose programming language, offers high-end scalability and can be used to define functions that have a single parameter. This article presents a simple guide to declaring a function with a single parameter in Dart.
Code snippet: Declaring a Single Parameter Function in Dart
void main() {
displayMessage('Hello Dart!');
}
void displayMessage(String message) {
print(message);
}
Code Explanation for Declaring a Single Parameter Function in Dart
In the provided code snippet, we have written a simple Dart program that declares a function with a single parameter. Let’s walk through it step by step:
- First, we define the
main()
function which is the entry point of every Dart application.
void main() {
displayMessage('Hello Dart!');
}
In this main()
function, we call another function displayMessage()
with the string parameter 'Hello Dart!'
.
- Next, we declare the
displayMessage()
function that has a single string parametermessage
.
void displayMessage(String message) {
print(message);
}
As we can see, displayMessage()
function is declared with void
as its return type indicating it doesn’t return a value. It accepts a single argument message
of type String
. The function prints whatever message it receives as an argument.
- When this program is executed, the
displayMessage()
function is called from the main function with the string ‘Hello Dart!‘. ThedisplayMessage()
function receives this string and prints it.
This is a basic example on how to declare a function with a single parameter in Dart. This can be expanded with more complex logic inside the function to use the parameter effectively.