DEV Community

Cover image for Dart basics - part 3
kururu
kururu

Posted on

Dart basics - part 3

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";
}
Enter fullscreen mode Exit fullscreen mode

you can invoke this function using callbacks way:

getMyName().then((value){
    print(value);
  });
Enter fullscreen mode Exit fullscreen mode

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();
  }
}
Enter fullscreen mode Exit fullscreen mode

to invoke the function:

  var myName = Name('Kururu');
  var r =myName.capitalize();


      print(r);
Enter fullscreen mode Exit fullscreen mode

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);
  }

Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

to execute this anonymous function:

print(printMyName("Kururu For life"));

it is not clear , right:)

thanks for reading:)

Top comments (0)