INTRODUCTION
In this lecture, we're going to dive into the world of functions in Dart programming language. You will learn how to create reusable blocks of code that can take parameters, making your programming life easier. By the end of the lecture you will be able to:
- How to declare functions with parameters in Dart
- How to pass values to functions when invoking them
- Best practices for using functions with parameters in your Dart projects
WHAT ARE FUNCTIONS
Functions are like mini-programs within your program. They group related lines of code together, allowing you to organize your code in a logical and maintainable way. By using functions, you can:
- Avoid code duplication
- Improve code readability
- Make your code more modular and reusable
FUNCTIONS WITH PARAMETER
A function can have parameters, which are values passed to the function when it's invoked. Think of parameters like ingredients in a recipe. Just as a recipe might require specific ingredients to produce the desired dish, a function with parameters expects specific values to perform its task.
WHY USE FUNCTIONS WITH PARAMETER
Functions with parameters offer several benefits:
- Flexibility: You can reuse the same function with different inputs, making your code more versatile.
- Readability: By passing parameters, you can make your code more self-explanatory and easier to understand.
- Maintainability: If you need to make changes to your code, functions with parameters make it easier to update your code without affecting other parts of your program.
CODE SAMPLE
String studentInfo(String first_name, String
last_name){
String
details="Your First name is ${first_name} Last name is ${last_name}";
return
details;
}
void main(){
print(studentInfo("Joseph", "Ameh"));
}
EXPLANATION
Line 1: Declare a function of type string called studentInfo with 2 parameters of type String
Line 2 : Declare a variable called details that stores the student using string interpolation.
Line 3: Return the detail and end the function
Line 5: Is the main function. It is the entry point of the function
Line 6: Invoke the function studentInfo and 2 values are passed to it which are separated by comma.
TRY IT YOURSELF
Extend the code to include 1 more parameter middle name then print both the first, middle and last name.
CONCLUSION
In this tutorial, we've explored the fundamentals of creating functions with parameters in Dart. We've covered the basics of functions, parameters, and their benefits, followed by a step-by-step guide on implementing functions with parameters. With clear code explanations and practical examples, you're now equipped to apply this knowledge to real-world problems. By diligently following this guide, you should be able to confidently create and use functions with parameters in your Dart projects.
Tags:
Dart