Flutter – Working with Callback Functions

21 Jun, 2022
In this article, we will see how we can use callback functions in flutter. We will learn about different methods to implement callback functions in flutter. Callback is basically a function or a method that we pass as an argument into another function or a method to perform an action. In the simplest words, we can say that Callback or VoidCallback are used while sending data from one method to another and vice-versa. It is very important to maintain a continuous flow of data throughout the flutter app.
Let’s assume that you are working on an app.  This app displays some sort of data.  Now to alter the values in the application, there are 2 approaches that you can take, either change the state using various state-altering techniques or change the value using a Callback. If we are to work with the Callback function there are 2 possible methods that we can use as shown below:
In this approach, we just define the function that is supposed to trigger a callback when a specific event occurs.
Example:
Dart
import 'package:flutter/material.dart';  // function to trigger the app build processvoid main() {  runApp(MaterialApp(    home: Scaffold(      // appbar      appBar: AppBar(        title: const Text('GeeksForGeeks'),        backgroundColor: const Color.fromRGBO(15, 157, 88, 1),      ),      body: const MyApp(),    ),  ));} class MyApp extends StatefulWidget {  const MyApp({Key? key}) : super(key: key);  @override  // ignore: library_private_types_in_public_api  _MyAppState createState() => _MyAppState();} class _MyAppState extends State<MyApp> {  int count = 0;  @override  Widget build(BuildContext context) {    return Center(      child: Column(        mainAxisAlignment: MainAxisAlignment.center,        children: [          Text(            '$count',            style: const TextStyle(fontSize: 50.0),          ),          ElevatedButton(            style: ButtonStyle(                backgroundColor: MaterialStateProperty.all(Colors.green)),            onPressed: () {              setState(() {                count++;              });            },            child: const Text(''                'increase'),          ),           // RaisedButton is deprecated and shouldn't be used.          // Use ElevatedButton insetad.                     // RaisedButton(          //   // callback function          //   // this increments the value          //   // by 1 each time the Raised button is pressed          //   onPressed: () {          //     setState(() {          //       count++;          //     });          //   },          //   child: const Text(''          //       'increase'),          // )        ],      ),    );  }}
Output:
In this approach, the callback is directly passed to the event. As shown in the below example, the onPressed action makes the direct callback  function defined in the earlier part of the code. 
Example: 
Dart
import 'package:flutter/material.dart'; void main() {  runApp(MaterialApp(    home: Scaffold(      // appbar      appBar: AppBar(        title: const Text('GeeksForGeeks'),        backgroundColor: const Color.fromRGBO(15, 157, 88, 1),      ),      body: const MyApp(),    ),  ));} class MyApp extends StatefulWidget {  const MyApp({Key? key}) : super(key: key);   @override  // ignore: library_private_types_in_public_api  _MyAppState createState() => _MyAppState();} class _MyAppState extends State<MyApp> {  int count = 0;   // callback function  callBack() {    setState(() {      count++;    });  }   @override  Widget build(BuildContext context) {    return Center(      child: Column(        mainAxisAlignment: MainAxisAlignment.center,        children: [          Text(            '$count',            style: const TextStyle(fontSize: 50.0),          ),          ElevatedButton(            style: ButtonStyle(                backgroundColor: MaterialStateProperty.all(Colors.green)),            onPressed: callBack,            child: const Text('increase'),          ),           // RaisedButton is deprecated and shouldn't be used.          // Use ElevatedButton insetad.           // RaisedButton(          //   // callback on Button press          //   onPressed: callBack,          //   child: Text(''          //       'increase'),          // )        ],      ),    );  }}
Output:
ankit_kumar_
android
Flutter
Picked
Dart
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.