Updated 29 December 2023
In this article, we are going to learn about the Callable classes in Dart.
Read more about our Flutter app development services.
As the name “Callable” points out for calling something. Dart facilitates us to call the class instances like a function with the help of the Call() function.
Basically, If we want to call a class instance as a function then we need to implement the call() function in it.
The call () method supports the same functionality as normal functions such as parameters and return types.
1 2 3 4 5 6 7 8 |
class your_class_name { return_type call ( parameters ) { ... // function code } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class myCallableClassExample { String call(String a, String b, String c) => ' $a $b $c !'; // call method which to make create the class callable } void main() { // Creating instance of class var callableClassInstance = myCallableClassExample(); var callableClassReturn = callableClassInstance('Hello', 'Team', 'Mobikul'); print(callableClassReturn); } |
Result:
Callable function example for int return type
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class myCallableClassExample { int call (int a,int b, int c)=>a+b+c;// call method make create the class callable } void main() { var callableClassInstance = myCallableClassExample();// Creating instance of class var callableClassReturn = callableClassInstance(5, 10, 15); print(callableClassReturn); } |
Result:
Till now, we know about call function and how to implement them to make a class callable.
Now A question arises, Can we create multiple call functions for a class?
The answer is NO. Dart doesn’t allow us to create multiple call()
functions for a class.
Let’s check it with an example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class myCallableClassExample { int call (int a,int b, int c)=>a+b+c;// Fisrt call method make create the class callable int call (int a,int b, int c)=>a+b+c;// Second call method } void main() { var callableClassInstance = myCallableClassExample();// Creating instance of class var callableClassReturn = callableClassInstance(5, 10, 15); print(callableClassReturn); } |
Result:
In this article, we have checked about callable classes and call() function.
Thanks for Reading.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.