in the previous topic we learn how to create and invoke a function.
in this topic we are going to learn some advance functions.
** Callback Function**
Callback is basically a function or a method that we pass as an argument into another function or a method to perform an action
Imagine you have a function that return a future value
and you try to invoke it in non-future function then you have to use callback syntax:
Future getMyName()async {
await Future.delayed(Duration(seconds:5));
return "Kururu is Beast";
}
you can invoke this function using callbacks way:
getMyName().then((value){
print(value);
});
after 5 seconds will print
Kururu is Beast
also the callback function can be use with extension
class Name{
String name;
Name(this.name);
}
extension capitalizeName on Name{
String capitalize(){
return this.name.toUpperCase();
}
}
to invoke the function:
var myName = Name('Kururu');
var r =myName.capitalize();
print(r);
Higher Order Functions
higher-order function that can be passed as a parameter .
i find another definition in this post
In dart programming language can accept a function as an argument, this type of functions is called higher order functions.
String getUser()=> "Kururu";
void printUser(String Function() getUser)
{
// getting user maybe it's from api like etc.
String user = getUser();
// and print the user.
print(user);
}
to invoke printUser you have to pass a function that return a string and not accept any parameter which is getUser in our example
printUser(getUser);
And there are many higher-order functions related to List and String , etc.
*Lambda Expression *
lambda expression is a function without name
to create a lambda function use Function keyword
Function printMyName = (String name) =>name;
to execute this anonymous function:
print(printMyName("Kururu For life"));
it is not clear , right:)
thanks for reading:)
Top comments (0)