Menu
CoddyTech

Pass a Callback to a Child

Part of the State Management section of Coddy's Flutter journey. Lesson 2 of 27.

A value goes down from parent to child. A tap goes the other way: the button is in the child, but the score it changes belongs to the parent.

The parent hands the child a function, and the child calls it. A function with no parameters that returns nothing has the type VoidCallback:

class AddButton extends StatelessWidget {
  const AddButton({super.key, required this.onAdd});

  final VoidCallback onAdd;

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(onPressed: onAdd, child: Text('Add point'));
  }
}

The parent writes what the tap does, with setState as usual:

AddButton(
  onAdd: () {
    setState(() {
      score++;
    });
  },
)

Write onPressed: onAdd, not onAdd(). The first hands the function to the button for later. The second calls it right away while building, and passes what it returns.

challenge icon

Challenge

Easy

The Add point button lives in the AddButton widget, and it does nothing yet.

  • Give AddButton a final VoidCallback onAdd field, set by its constructor.
  • Use it as the button's onPressed.
  • In the page, pass a function that adds 1 to score inside setState.

Try it yourself

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int score = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('Score: $score', style: const TextStyle(fontSize: 32)),
            const SizedBox(height: 16),
            const AddButton(),
          ],
        ),
      ),
    );
  }
}

class AddButton extends StatelessWidget {
  const AddButton({super.key});

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {},
      child: const Text('Add point'),
    );
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in State Management

Practice on your own: Online Flutter compiler