In Dart, a function is a block of code that performs a specific task, can take inputs, and may return a result. Functions help organize code, make it reusable, and improve readability. Dart functions are first-class objects, meaning they can be assigned to variables, passed as arguments, and returned from other functions. Functions in Dart support both named and positional parameters and offer optional parameters and default values.
In Dart, a function is a block of reusable code that performs a specific task.
Functions help organize code, make it more readable, and allow for reuse without rewriting the same code.
Dart supports different types of functions, including named functions, anonymous functions, and arrow functions.
returnType functionName(parameters) {
// function body
return value; // optional
}
returnType: The data type of the value the function returns. Use void if the function doesn’t return anything.
functionName: The name of the function.
parameters: The input values that the function takes (optional).
return: Returns a value from the function (optional).
Adds two numbers and returns the result:
Function-
int add(int a, int b) {
return a + b;
}
void main() {
int result53 = add(5, 3); // function calling
print("The result is: $result53");
int result32 = add(3,2); // function calling
print("The result is: $result32");
}
If a function doesn’t return any value, you can specify the return type as void.
Example:
void greet(String name) {
print("Hello, $name!");
}
void main() {
greet("Alice");
}
In Dart, you can make parameters optional by enclosing them in square brackets [].
Optional parameters have a default value of null unless you specify a default value.
Example:
void describe(String name, [int? age])
{
if (age != null) {
print("$name is $age years old.");
} else
{
print("Name is $name.");
}
}
void main() {
describe("Bob", 25);
describe("Alice"); // without passing age parameter
}
Named parameters allow you to specify which parameter to set when calling the function, making code more readable. Named parameters are enclosed in curly braces {}.
Example:
void displayInfo({String? name, int? age}) {
print("Name: $name, Age: $age");
}
void main() {
displayInfo(name: "John", age: 30);
displayInfo(age: 22, name: "Emma"); // order doesn't matter
}
Arrow functions are shorthand for functions that contain only one expression. They are defined using => instead of {}.
Example:
int multiply(int a, int b) => a * b;
void main() {
print(multiply(4, 5)); // Outputs: 20
}
An anonymous function is a function without a name. It’s often used as an argument in higher-order functions like forEach.
Example:
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
numbers.forEach((number) {
print(number * 2);
});
}
You can also assign default values to parameters, which are used if no value is passed for that parameter.
Example:
void greet(String name, [String greeting = "Hello"]) {
print("$greeting, $name!");
}
void main() {
greet("Alice"); // Uses default greeting
greet("Bob", "Hi"); // Uses provided greeting
}
A higher-order function is a function that can take another function as a parameter or return a function.
Example:
void main() {
// Passing a function as a parameter
List<int> numbers = [1, 2, 3];
numbers.forEach(printDouble); // Calls printDouble for each number
}
void printDouble(int number) {
print(number * 2);
}
Defined outside of main()-
void main()
{
greet(); // Function call
}
void greet() // Function definition
{
print("Hello, welcome to Dart!");
}
Defined inside of main()-
void main() {
// Function definition
void greet() {
print("Hello, welcome to Dart!");
}
// Function call
greet();
}
-----------------------------------------------------------------------------------------------------------------------------------------------
void main() {
int sum = add(5, 10);
print("Sum: $sum");
}
int add(int a, int b) {
return a + b;
}
void main() {
print(isEven(4)); // true
print(isEven(7)); // false
}
bool isEven(int number) {
return number % 2 == 0;
}
void main() {
print("Factorial of 5: ${factorial(5)}");
}
int factorial(int number) {
if (number <= 1) return 1;
return number * factorial(number - 1);
}
void main() {
print("Area of circle with radius 3: ${circleArea(3)}");
}
double circleArea(double radius) {
const double pi = 3.14159;
return pi * radius * radius;
}
void main() {
print(isPalindrome("madam")); // true
print(isPalindrome("hello")); // false
}
bool isPalindrome(String text) {
String reversed = text.split('').reversed.join('');
return text == reversed;
}
void main() {
print("Max of 10, 20, 15: ${maxOfThree(10, 20, 15)}");
}
int maxOfThree(int a, int b, int c) {
return (a > b && a > c) ? a : (b > c ? b : c);
}
void main() {
print("30°C in Fahrenheit: ${celsiusToFahrenheit(30)}");
}
double celsiusToFahrenheit(double celsius) {
return (celsius * 9 / 5) + 32;
}
void main() {
fibonacci(5); // 0 1 1 2 3
}
void fibonacci(int n) {
int a = 0, b = 1;
for (int i = 0; i < n; i++) {
print(a);
int temp = a;
a = b;
b = temp + b;
}
}
void main() {
print("Vowels in 'hello': ${countVowels("hello")}");
}
int countVowels(String str) {
int count = 0;
for (var char in str.toLowerCase().split('')) {
if ('aeiou'.contains(char)) {
count++;
}
}
return count;
}
void main() {
print("GCD of 48 and 18: ${gcd(48, 18)}");
}
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
void main()
{
greet(); // Function call
}
void greet() // Function definition
{
print("Hello, welcome to Dart!");
}
Ex=
void main()
{
display(); //calling
}
display()
{
print('defining outside'); //Defining
}
-----------------------------------------------------------------------------------------------------------------------------------------------------------
A function in Dart is defined using the following syntax:
returnType functionName(parameters)
{
// Function body
return value;
}
returnType: Specifies the type of value returned by the function (e.g., int, String, void). If the function does not return anything, void is used.
functionName: The name of the function.
parameters: Input values that the function can take, separated by commas.
return: The keyword return sends a value back to where the function was called.
int add(int a, int b)//Defining function
{
return a + b;
}
void main() {
int sum = add(5, 3); //calling function
print("Sum: $sum"); // Output: Sum: 8
}
For simple functions with one expression, Dart allows using arrow syntax (=>) to define the function:
int multiply(int a, int b) => a * b; //Syntaxt:- returnType functionName(parameters) => return values;
void main() {
print(multiply(4, 5)); // Output: 20
}
Dart functions can have optional parameters, either positional or named.
Optional Positional Parameters
These are wrapped in square brackets []. If not provided, they are null by default unless a default value is specified.
void greet(String name, [String? message]) {
print("Hello $name! ${message ?? ''}");
}
void main() {
greet("Alice"); // Output: Hello Alice!
greet("Alice", "Welcome!"); // Output: Hello Alice! Welcome!
}
Optional Named Parameters
Named parameters are enclosed in curly braces {}. You can make them required using required, or assign default values.
void displayInfo(String name, {int age = 18, required String city}) {
print("$name, Age: $age, City: $city");
}
void main() {
displayInfo("Bob", city: "New York"); // Output: Bob, Age: 18, City: New York
}
Optional parameters can have default values, which are used if no argument is passed for that parameter.
void greet(String name, [String message = "Welcome!"]) {
print("Hello $name! $message");
}
void main() {
greet("Alice"); // Output: Hello Alice! Welcome!
}
Anonymous functions are functions without a name. They are often used as arguments to higher-order functions like map, forEach, etc.
void main() {
var numbers = [1, 2, 3];
numbers.forEach((num) {
print(num * 2); // Output: 2, 4, 6
});
}
Dart supports higher-order functions, meaning functions can take other functions as parameters or return functions.
void executeOperation(int a, int b, Function operation) {
print("Result: ${operation(a, b)}");
}
int add(int x, int y) => x + y;
void main() {
executeOperation(5, 3, add); // Output: Result: 8
}
A closure is a function that captures variables from its surrounding scope. This allows the function to use and modify variables even after the outer function has finished executing.
Function createCounter() {
int count = 0;
return () {
count += 1;
return count;
};
}
void main() {
var counter = createCounter();
print(counter()); // Output: 1
print(counter()); // Output: 2
}
A recursive function is one that calls itself, often used to solve problems that can be broken down into smaller, similar sub-problems.
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
void main() {
print(factorial(5)); // Output: 120
}
If a function doesn’t return any value, it can be defined with a void return type.
void greet() {
print("Hello, World!");
}
void main() {
greet(); // Output: Hello, World!
}
void main()
{
// Function definition
void greet() {
print("Hello, welcome to Dart!");
}
// Function call
greet();
}
Ex=
void main()
{
void display() // Defining
{
print('Function define inside'); //defined than calling
}
display(); //calling
}
---------------------------------------------------------
void main()
{
int add(int a, int b){
return a+b;
}
print('Sum= ${add(2,3)}');
print('Sum 3,4= ${add(5,8)}');
}
void main() {
bool isEven(int number) {
return number % 2 == 0;
}
print(isEven(7) ? "Even" : "Odd"); //Calling & Output: Odd
}
void main()
{
int factorial(int n){
if (n<=1) return 1;
return n*factorial(n-1);
}
print('Factorial of 3: ${factorial(3)}');
print('Factorial of -2: ${factorial(-2)}');
}
void main() {
bool isPalindrome(String str) {
return str == str.split('').reversed.join('');
}
print(isPalindrome("radar")); // Output: true
print(isPalindrome("hello")); // Output: false
}
void main()
{
int maxOfThree(int a, int b, int c){
return (a>b && a>c)?a:(b>c?b:c);
}
print('Maxof1,9,5: ${maxOfThree(1, 9, 5)}');
print('Maxof-1,7,5: ${maxOfThree(-1, 7, 5)}');
print('Maxof1,1,0: ${maxOfThree(1, 1, 0)}');
}
void main() {
double celsiusToFahrenheit(double celsius) {
return (celsius * 9 / 5) + 32;
}
print("30°C in Fahrenheit: ${celsiusToFahrenheit(30)}"); // Output: 86.0
}
void main() {
int countVowels(String str) {
int count = 0;
for (var char in str.toLowerCase().split('')) {
if ('aeiou'.contains(char)) {
count++;
}
}
return count;
}
print("Vowels in 'hello': ${countVowels("hello")}"); // Output: 2
}
void main() {
bool isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= n ~/ 2; i++) {
if (n % i == 0) return false;
}
return true;
}
print("Is 7 prime? ${isPrime(7)}"); // Output: true
print("Is 10 prime? ${isPrime(10)}"); // Output: false
}
void main() {
void fibonacci(int n) {
int a = 0, b = 1;
for (int i = 0; i < n; i++) {
print(a);
int temp = a;
a = b;
b = temp + b;
}
}
fibonacci(5); // Output: 0 1 1 2 3
}
void main() {
double circleArea(double radius) {
const double pi = 3.14159;
return pi * radius * radius;
}
print("Area of circle with radius 3: ${circleArea(3)}"); // Output: 28.27431
}
Functions can accept parameters to work with different inputs.
void main()
{
display('Sandeep');
display('Pradeep');
}
void display(String name)
{
print('Name is: $name');
}
Ex=
void main() {
// Function that takes a name and prints a personalized message
void greet(String name) // name as parameter
{
print("Hello, $name! Welcome to Dart!");
}
// Calling the function with an argument
greet("Alice"); // calling with parameter
greet("Bob");
}
------------------------------------------------------------------------------------------------------------------------------
1. Add Two Numbers
void main() {
int sum = add(5, 10);
print("Sum: $sum");
}
int add(int a, int b) {
return a + b;
}
2. Calculate Area of a Circle
void main() {
double areaOfCircle(double radius) {
const double pi = 3.14159;
return pi * radius * radius;
}
print("Area of circle: ${areaOfCircle(4)}"); // Output: 50.26544
}
3. Convert Celsius to Fahrenheit
void main() {
double celsiusToFahrenheit(double celsius) {
return (celsius * 9 / 5) + 32;
}
print("30°C in Fahrenheit: ${celsiusToFahrenheit(30)}"); // Output: 86.0
}
4. Check if a Number is Even or Odd
void main() {
bool isEven(int number) {
return number % 2 == 0;
}
print(isEven(4) ? "Even" : "Odd"); // Output: Even
print(isEven(7) ? "Even" : "Odd"); // Output: Odd
}
5. Find Maximum of Three Numbers
void main() {
int maxOfThree(int a, int b, int c) {
return (a > b && a > c) ? a : (b > c ? b : c);
}
print("Max: ${maxOfThree(5, 10, 8)}"); // Output: Max: 10
}
6. Print a Greeting Message
void main() {
void greet() {
print("Hello, welcome to Dart programming!");
}
greet(); // Output: Hello, welcome to Dart programming!
}
7. Print the Current Date and Time
void main() {
void printCurrentDateTime() {
DateTime now = DateTime.now();
print("Current Date and Time: $now");
}
printCurrentDateTime(); // Output: Current Date and Time: [current date and time]
}
8. Print First 10 Fibonacci Numbers
void main() {
void printFibonacci() {
int a = 0, b = 1;
for (int i = 0; i < 10; i++) {
print(a);
int temp = a;
a = b;
b = temp + b;
}
}
printFibonacci(); // Output: First 10 Fibonacci numbers
}
9. Display a Simple Message
void main() {
void showMessage() {
print("This is a simple message without any parameters.");
}
showMessage(); // Output: This is a simple message without any parameters.
}
10. Print Numbers from 1 to 5
void main() {
void printNumbers() {
for (int i = 1; i <= 5; i++) {
print(i);
}
}
printNumbers(); // Output: 1 2 3 4 5
}
Functions can return values to the caller using the return keyword.
void main() {
// Function that calculates the square of a number
int square(int num)
{
return num * num;//function returning
}
// Calling the function and printing the result
int result = square(4);
print("The square of 4 is: $result");
}
Ex=
void main() {
// Function that calculates the square of a number
int square(int num) {
int square = num * num;
return square; //function returning
}
// Calling the function and printing the result
int fourSq = square(4);
print("The square of 4 is: $fourSq");
}
A function with a return value sends back a result to where it was called using the return keyword.
(Same to above examples)
1. Add Two Numbers and Return the Sum
void main() {
int add(int a, int b) {
return a + b;
}
int result = add(5, 3);
print("Sum: $result"); // Output: Sum: 8
}
2. Calculate and Return Area of a Circle
void main() {
double areaOfCircle(double radius) {
const double pi = 3.14159;
return pi * radius * radius;
}
double area = areaOfCircle(4);
print("Area of circle: $area"); // Output: Area of circle: 50.26544
}
3. Convert Celsius to Fahrenheit and Return the Result
void main() {
double celsiusToFahrenheit(double celsius) {
return (celsius * 9 / 5) + 32;
}
double fahrenheit = celsiusToFahrenheit(30);
print("30°C in Fahrenheit: $fahrenheit"); // Output: 86.0
}
4. Find and Return the Maximum of Three Numbers
void main() {
int maxOfThree(int a, int b, int c) {
return (a > b && a > c) ? a : (b > c ? b : c);
}
int max = maxOfThree(5, 10, 8);
print("Max: $max"); // Output: Max: 10
}
5. Calculate and Return the Factorial of a Number
void main() {
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
int result = factorial(5);
print("Factorial of 5: $result"); // Output: 120
}