Google News
logo
Dart - Interview Questions
How do you define a function in Dart?
In Dart, you can define a function using the following syntax:
returnType functionName(parameter1, parameter2, ...) {
  // Function body
  // Code statements
  // Optional return statement
}​

Let's break down the parts of a function declaration in Dart :

* returnType : The `returnType` represents the type of value that the function returns. It can be any valid Dart type, such as `void`, `int`, `String`, etc. If the function does not return a value, the `void` keyword is used.

* functionName : The `functionName` is the identifier for the function. It should follow Dart naming conventions and describe the purpose or action performed by the function.

* parameters : Parameters are optional, and they define the inputs to the function. They are enclosed in parentheses and separated by commas. Each parameter consists of a type and a name, e.g., `int a, String b`. You can also specify default values for parameters.

* function body : The function body contains the code statements that define the behavior of the function. It is enclosed in curly braces `{}`. You write the necessary code statements to perform the desired operations or calculations within the function.

* return statement : If the function has a non-void return type, you can use the `return` keyword followed by an expression to return a value from the function. The return statement is optional in void functions.
Here's an example of a simple function in Dart :
int sum(int a, int b) {
  int result = a + b;
  return result;
}​

In the example above, we define a function named `sum` that takes two `int` parameters (`a` and `b`). The function body calculates the sum of the parameters and stores it in the `result` variable. Finally, the `result` is returned using the `return` statement.

You can call the function by using its name followed by parentheses, passing arguments if necessary:
int total = sum(5, 3);
print(total); // Output: 8​

The function is invoked using the name `sum`, and the arguments `5` and `3` are passed to the function. The returned value is stored in the `total` variable and printed to the console.

You can define functions with different return types, different numbers of parameters, and different combinations of parameter types based on your specific requirements.
Advertisement