DEV Community

Cover image for Dart Programming || Functions || Arguments || Return type || Exercises
Hosney Ara Smrity
Hosney Ara Smrity

Posted on

Dart Programming || Functions || Arguments || Return type || Exercises

Dart is a Powerful language, it’s a new platform for modern App, Web, Game, A.I. development. It’s a superb place to start learning to program.

Watch on Youtube

Functions are not strictly necessary to write programs. We usually use functions to split a large task into simpler operations or to implement operations that we will use
repeatedly in our application.

Let’s see how to define functions in Dart.

function_name(function_arguments) {
// Body of the function
}

Here you can see a very simple function example:

greet(name) {
print('Welcome to Dart $name');
}

If you want to execute this function from your main program, you only need to call it, like this:

void main() {
greet('John'); // Executing our sample function.
}

Although the above code is perfectly valid, it is recommended to use the Dart code style guide. Therefore, you should always specify the return data type of the function and the data types of the parameters passed to the function when you define your functions. Thus, our function declaration should look like this:

return_type function_name(argument_type argument) {
// body of the function.
}

Continuing with our example, let’s change the greeting:

void greet(String name) {
print('Welcome to Dart $name');
}

To properly declare a function in Dart and following the code style guide you must specify:

• Function return type or void if the function did not return any value.
• Function name.
• Function parameters specifying data type and name of each parameter.
• Body of the function, between curly braces.

To show you the return data type and how a function will return any value, our sample function will be redeclared as follows:

String greet(String name) {
String msg = 'Welcome to Dart $name';
return msg;
}

More about Arguments & Return type on Youtube

Get in Touch with the Instructor

Do you have questions or comments? Do you need help working through an example or exercise? Please, do not hesitate to reach out on e-mail at h.a.smrity24@gmail.com.

Discussion (0)