Functions are essential building blocks in Dart programming. They allow you to organize code into reusable units, making your programs more modular and easier to maintain.
In Dart, functions are declared using the following syntax:
returnType functionName(parameters) {
// Function body
return value;
}
Here's a simple example of a function that adds two numbers:
int add(int a, int b) {
return a + b;
}
Dart functions can have various types of parameters:
For more details on function parameters, check out the Dart Function Parameters guide.
Functions in Dart can return values using the return
keyword. If no return type is specified, the function defaults to returning dynamic
.
String greet(String name) {
return "Hello, $name!";
}
Learn more about Dart Return Values in our dedicated guide.
Functions that don't return a value are called void functions. They're declared with the void
keyword:
void printGreeting(String name) {
print("Hello, $name!");
}
In Dart, functions are first-class objects. This means you can assign them to variables, pass them as arguments, or return them from other functions.
var sayHello = (String name) => print("Hello, $name!");
sayHello("Alice"); // Outputs: Hello, Alice!
As you progress in Dart programming, explore these advanced function-related topics:
Understanding these function basics will set a solid foundation for your Dart programming journey. Practice writing various functions to reinforce your learning and improve your coding skills.