
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Functions in Dart Programming
Dart is a true object-oriented programming language. Even functions have their type in dart. Functions can be assigned to a variable and we can even pass them to another function as well. Functions in Dart are also objects, like everything else.
Let's create a simple function that accepts an integer as an argument and returns a bool value.
Example
Consider the example shown below −
bool isOdd(int x){ return x % 2 == 1; } void main() { bool ans = isOdd(3); print(ans); }
In the above code, we have two functions, one is the main() function whose return type is void and another is the isOdd() function that we just created which accepts an int data type variable as an argument and checks whether that number is odd in nature or not and returns the Boolean value.
Output
true
We can have any returned data type we want for our function.
Example
Consider another example of a function with a different data type shown below &mnus;
String returnMyName(String name){ return "Your name is ${name}"; } void main() { String ans = returnMyName("Mukul"); print(ans); }
This time, in our function returnMyName, we passed a String argument and also the return type is a String.
Output
Your name is Mukul
Dart also provides a shorthand syntax that we can use to make our code more compact.
Example
Consider the example shown below −
String returnMyName(name) => name + " Point"; void main() { String ans = returnMyName("Tutorials"); print(ans); }
In the above example, we created a function returnMyName whose return data type is a String and then we used the "=>" operator instead of the standard code block.
Output
Tutorials Point
There are certain possible cases where we want to have some default value of the parameter variable, Dart allows us to do that.
Example
Consider the example shown below −
void sumOfNumbers(int a, int b, [int c = 5]){ print(a + b + c); } void main() { sumOfNumbers(2,4); sumOfNumbers(2,4,10); }
In the above example, the function sumOfNumbers() have three parameters, and the third parameters is a named parameter whose default value is provided in case we don't pass any value to it when invoking the function.
Output
11 16