How to Use VoidCallback and Function(x) Callbacks to Communicate Between Widgets in Flutter

In Flutter, communication between widgets can use VoidCallback and Function Callback.

VoidCallbacks are callbacks that don’t return a value to the Parent Widget. This is useful if we only want to notify the Parent Widget of events that occurred on the Child Widget.

The Function Callback is a callback that notifies the Parent Widget of an event that occurs in the Child Widget and also returns a value to the Parent Widget.

typedef VoidCallback = void Function();

VoidCallbacks and Function Callbacks are both functions. The only difference is that VoidCallback has no arguments and returns no data.

In this article, Bardimin will give a simple example of using VoidCallback and Function Callback in a simple application

1. Create a new Flutter project

As a first step, create a new Flutter project with Android Studio. You can check out the Flutter and Android Studio integration in the article How to Easily Install Flutter on Android Studio and Windows.

TOP TUTORIALS:  [Yii2] How to create and use Functions on Yii2

Once the new project is created, we will modify the sample file to create a simple application that uses VoidCallback and Function Callback.

In the file “main.dart” change as follows.

import 'package:flutter/material.dart';
import 'parent_widget.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const ParentWidgetPage(title: 'Flutter VoidCallback & Function Callback'),
    );
  }
}

2. Create a Parent Widget

Then create a new file with the name “ parent_widget.dart ”. In this file, we will create the “_voidCallback” and “_functionCallback” functions, which we will call from the Child Widget.

We will call the “_voidCallback” function using “VoidCallback”.

  void _voidCallback() {
    setState(() {
      _counter++;
    });
  }

We will call the function “_functionCallback(int i)” with parameters using “Function(x) Callback”.

  void _functionCallback(int i) {
    setState(() {
      _counter += i;
    });
  }

The “parent_widget.dart” file that we created is complete as follows.

import 'package:flutter/material.dart';
import 'voidcallback_child_widget.dart';
import 'function_child_widget.dart';

class ParentWidgetPage extends StatefulWidget {
  const ParentWidgetPage({Key? key, required this.title}) : super(key: key);
  final String title;
  @override
  State<ParentWidgetPage> createState() => _ParentWidgetPageState();
}

class _ParentWidgetPageState extends State<ParentWidgetPage> {
  int _counter = 0;

  void _voidCallback() {
    setState(() {
      _counter++;
    });
  }

  void _functionCallback(int i) {
    setState(() {
      _counter += i;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      floatingActionButton: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            VoidChildWidgetPage(voidCallback: _voidCallback),
            FunctionChildWidgetPage(functionCallback: _functionCallback),
          ],
        ),
      ),
    );
  }
}

3. Create a VoidCallback Child Widget

Next, create a file “ voidcallback_child_widget.dart ”. In this file, we will create a button that will call the “_voidCallback” function in the “parent_widget.dart” file.

import 'package:flutter/material.dart';

class VoidChildWidgetPage extends StatelessWidget {
  final VoidCallback voidCallback;

  const VoidChildWidgetPage({Key? key, required this.voidCallback})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () => voidCallback(),
      child: const Text("Void Callback"),
    );
  }
}

4. Create a Function Callback Child Widget

Then create a file ” function_ child_widget.dart”. Just like before, in this file, we will also create a button that will call the function “_functionCallback(int i)” in the file “parent_widget.dart” which will return an integer value.

import 'package:flutter/material.dart';

class FunctionChildWidgetPage extends StatelessWidget {
  final Function(int) functionCallback;

  const FunctionChildWidgetPage({Key? key, required this.functionCallback})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () => functionCallback(5),
      child: const Text("Fx Callback"),
    );
  }
}

Then run the project. On the emulator, you will see there are two buttons, namely the “VoidCallback” and “Fx Callback” buttons.

TOP TUTORIALS:  [yii2] How to create new extensions without version or Git controls
void callback

If you click the “VoidCallback” button, the VoidCallback Child Widget will simply call the “_voidCallback” function on the Parent Widget returning no value.

Meanwhile, if you click the “Fx Callback” button, the Function Callback Child Widget will call the “_functionCallback(int i)” function on the Parent Widget by returning an integer value.