Skip to main content

How to use call back function in Flutter

 Call back functions in Flutter


In Flutter, callbacks are often used to pass functions as arguments to other functions or widgets. Callbacks are a way to handle events or communicate between different parts of your application. Here's how you can use callback functions in Flutter-


1. **Define the Callback Function:**

   Start by defining the callback function. This is the function that will be called when a certain event occurs. For example:


   ```dart

   typedef MyCallback = void Function(String result);

   ```


   Here, `MyCallback` is a typedef for a function that takes a `String` argument and returns `void`.


2. **Pass the Callback Function:**

   You can pass the callback function as an argument to another function or widget. For instance, if you're creating a custom widget that needs to notify the parent when something happens, you would pass the callback as an argument to the widget constructor:


   ```dart

   class MyCustomWidget extends StatelessWidget {

     final MyCallback callback;


     MyCustomWidget({required this.callback});


     // Widget build method and other code...

   }

   ```


3. **Call the Callback Function:**

   Inside your widget or function, when the event you're interested in occurs, you can call the callback function. This allows you to pass data or notify the parent widget about the event:


   ```dart

   class MyCustomWidget extends StatelessWidget {

     final MyCallback callback;


     MyCustomWidget({required this.callback});


     void _onButtonPressed() {

       // Some event occurs, call the callback with data

       callback("Button Pressed");

     }


     @override

     Widget build(BuildContext context) {

       return ElevatedButton(

         onPressed: _onButtonPressed,

         child: Text("Press Me"),

       );

     }

   }

   ```


4. **Using the Callback:**

   In the parent widget, where you're using your custom widget, you can provide the callback function to handle the event:


   ```dart

   class ParentWidget extends StatelessWidget {

     void _handleCallback(String result) {

       print("Callback Result: $result");

       // Do something with the result

     }


     @override

     Widget build(BuildContext context) {

       return MaterialApp(

         home: Scaffold(

           appBar: AppBar(title: Text("Callback Example")),

           body: Center(

             child: MyCustomWidget(callback: _handleCallback),

           ),

         ),

       );

     }

   }

   ```


In this example, when the button in the `MyCustomWidget` is pressed, the `_onButtonPressed` method is called, which in turn calls the callback function provided by the parent widget. This allows you to pass data or trigger actions in the parent widget based on the event in the child widget.


Remember that callbacks are a way to achieve communication between different parts of your app, but as your app grows in complexity, you might explore other patterns like using state management solutions (like Provider, Bloc, Riverpod) for more organized and scalable communication between widgets.

Comments

Popular posts from this blog

How to write a code of Encode and Decode json data in Dart language

 Encode and decode JSON data in dart language import 'dart:convert'; void main() {   // Original data as a Dart map   Map<String, dynamic> originalData = {     'field1': 'value1',     'field2': 42,     'field3': true,   };   // Encode the Dart map to JSON string   String jsonString = jsonEncode(originalData);   print('Original JSON String:');   print(jsonString);   // Encode the JSON string to base64   String base64EncodedString = base64.encode(utf8.encode(jsonString));   print('\nBase64 Encoded String:');   print(base64EncodedString);   // Decode the base64 string to JSON string   String decodedJsonString = utf8.decode(base64.decode(base64EncodedString));   print('\nDecoded JSON String:');   print(decodedJsonString);   // Decode the JSON string to a Dart map   Map<String, dynamic> decodedData = jsonDecode(decodedJsonString);   print('\nDecoded Dart Ma...

About of Free Learning Tech Point

  Welcome to Free Learning Tech Point , where knowledge meets accessibility. Our platform is dedicated to providing high-quality educational resources and e-learning opportunities to learners around the world, completely free of charge. Our Mission: At Free Learning Tech Point, we believe that education is a fundamental right, and everyone should have access to valuable learning materials. Our mission is to break down barriers to education by offering a diverse range of courses, tutorials, and resources across various subjects and disciplines. What Sets Us Apart: - Free Access: Our commitment is to make learning accessible to all. No subscription fees, no hidden costs – just free, open access to knowledge.    - Quality Content: We curate and create content that is both engaging and informative. Whether you're a student, professional, or lifelong learner, our resources are designed to cater to various learning styles and levels. - Diverse Subjects: From tech and science...

Privacy Policy Of Free Learning Tech Point

  Thank you for visiting Free Learning Tech Point . You can use our website, services, and products with the awareness that this Privacy Policy describes how we gather, use, disclose, and protect your personal information. 1- Information We Collect: We may collect personal information that you provide directly to us, such as your name, email address, and any other information you choose to provide when using our Services. We may also collect non-personal information, such as aggregated data and usage patterns. 2- How We Use Your Information: We may use the information we collect for various purposes, including but not limited to: Providing and improving our Services. Responding to your inquiries and requests. Analyzing usage patterns and trends. Sending you updates, newsletters, and other communications. Personalizing your experience on our platform. 3- Cookies and Similar Technologies: We may use cookies and similar technologies to collect information about your interactions with...