Skip to main content

Command Palette

Search for a command to run...

Dart: Callable class

Published
2 min read
Dart: Callable class

Dart allows the user to create a callable class which allows the instance of the class to be called as a function. To allow an instance of your Dart class to be called like a function, implement the call() method.

Syntax:

class class_name {
  ... // class content

  return_type call ( parameters ) {
    ... // call function content
  }

}

In the above syntax, we can see that to create a callable class we have to define a call method with a return type and parameters within it.

Example:

Example1: Single callable class

class Student {  
  String call(String name, int age) {  
              return('Student name is $name and Age is $age');  

           }  
}  
void main() {  
   Student stu = new Student();  
   var msg = stu('Ghoghari',21);     // Class instance called like a function.  
   print('Dart Callable class');  
   print(msg);  
}

Output

Dart Callable class
Student name is Ghoghari and Age is 21

Explanation:

In the above code, We defined a call() function in the class Student that takes two arguments String name, integer age and return a message with this information. Then, we have created the object of class Student and called it like a function.

var msg = stu('Ghoghari',21);

Example2: Multiple callable class

class Student {  
  String call(String name, int age) {  
              return('Student name is $name and Age is $age');  

           }  
}  

class Employee {  
  int call(int empid, int age) {  
              return('Employee id is ${empid} and Age is ${age}');  

           }  
}  

void main() {  
   Student stu = new Student();  

   Employee emp = new Employee();  

   var msg = stu('Jinali',21);  // Class instance called like a function.  
   var msg2 = emp(101,23);   // Class instance called like a function.  
   print('Dart Callable class');  
   print(msg);  
   print(msg2);  
}

Output

Dart Callable class
Student name is Jinali and Age is 21
Employee id is 101 and Age is 23

Explanation:

In the above code, we defined two callable functions in class Student and class Employee. The Employee class call() function accepts two parameters as String empid and int age. We called instances of both classes as callable functions.

 var msg = stu('Jinali',21);  
 var msg2 = emp(101,23);

Dart

Part 20 of 50

I'll be here to provide explanations, examples, and assistance as you explore the depths of Dart programming language. Together, we'll unravel the intricacies of Dart, from its fundamental concepts to

Up next

Dart: Libraries

Dart, an open-source programming language initially developed by Google, is designed for bother server-side and client-side applications. Its software development kit(SDK) includes the Dart VM compiler and a utility called dart2js, which converts Dar...

More from this blog

Flutter Journey with Jinali

141 posts