OneBite.Dev - Coding blog in a bite size

Declare A Simple Function In Dart

Code snippet for how to Declare A Simple Function In Dart with sample and detail explanation

Dart, a popular programming language known for building mobile, desktop, and web applications, makes function declaration a breeze for beginners and experts alike. In this article, we will demonstrate how to declare a simple function in Dart.

Code snippet: Declaring a Simple Function

Before proceeding, it’s important to note that Dart is an object-oriented language, and functions are the crucial building blocks when writing Dart program.

Here is a basic illustration of a function declaration in Dart:

void greetUser() {
  print('Hello, User!');
}

To call the function, simply use the function name followed by parentheses like this:

greetUser();

Code Explanation for Declaring a Simple Function

The function declaration takes place with the help of ‘void’ keyword. In Dart, void is a special type that indicates a lack of value or a future absence of value. It often used when a function doesn’t return a value.

The function name greetUser comes after the ‘void’ keyword. The function name is followed by parentheses ’()’ which may include optional parameters. Since our example is a function without parameters, our parentheses are empty.

The instructions for what the function should do are held within curly braces ’{}‘. The code within these braces is often referred to as the function’s body. In our case, it’s just one line: print('Hello, User!');. What this does is print the greeting ‘Hello, User!’ every time the function is called.

For calling the function, we simply write the function’s name followed by parentheses ’()‘. The code greetUser(); calls the function and executes the code defined within the function’s body.

That’s it! This is how you declare and call a simple function in Dart. As you delve deeper into Dart programming, you will go on to add parameters to your functions, and make them return values, but this example demonstrates the basic premise of how to declare a function.

dart