6 C
New York
Monday, December 11, 2023

How to pass functions to child widgets in Flutter

This article walks you through a complete example of passing functions from a parent widget to a child widget in Flutter (the child widget can be stateless or stateful, and the passed functions can be called with parameters).

The Child Is A Stateless Widget

Example Preview

We’ll build a small app that contains 2 widgets named HomePage (the parent) and ChildWidget (the child). The child widget has 2 buttons that will call a function passed from the parent (this function can print something to the terminal) when one of them gets pressed.Advertisements

Here’s how it works:

The Code

1. HomeWidget is implemented in home_page.dart and ChildWidget is implemented in a separate file named child_widget.dart. File structure:

.
??? child_widget.dart
??? home_page.dart
??? main.dart

2. The code in child_widget.dart:

import 'package:flutter/material.dart';

class ChildWidget extends StatelessWidget {
  final Function buttonHandler;
  const ChildWidget({Key? key, required this.buttonHandler}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        ElevatedButton(
            onPressed: () => buttonHandler('Hello'),
            child: const Text('Say Hello')),
        ElevatedButton(
            onPressed: () => buttonHandler('Goodbye'),
            child: const Text('Say Goodbye')),
      ],
    );
  }
}

Advertisements3. The code in home_page.dart:

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

import './child_widget.dart';

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

  void _passedFunction(String input) {
    if (kDebugMode) {
      print(input);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ChildWidget(
          buttonHandler: _passedFunction,
        ),
      ),
    );
  }
}

4. Wire up everything in main.dart:

// main.dart
import 'package:flutter/material.dart';
import './home_page.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Remove the DEBUG banner
      debugShowCheckedModeBanner: false,
      title: 'KindaCode.com',
      theme: ThemeData(
        primarySwatch: Colors.amber,
      ),
      home: const HomePage(),
    );
  }
}

The Child Is A Stateful Widget

We will continue to work with the example in the previous section. Everything remains the same except ChildWidget is now stateful. The code in child_widget.dart:

import 'package:flutter/material.dart';

class ChildWidget extends StatefulWidget {
  final Function buttonHandler;
  const ChildWidget({Key? key, required this.buttonHandler}) : super(key: key);

  @override
  State<ChildWidget> createState() => _ChildWidgetState();
}

class _ChildWidgetState extends State<ChildWidget> {
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        ElevatedButton(
            onPressed: () => widget.buttonHandler('Hello'),
            child: const Text('Say Hello')),
        ElevatedButton(
            onPressed: () => widget.buttonHandler('Goodbye'),
            child: const Text('Say Goodbye')),
      ],
    );
  }
}

Conclusion

Advertisements

We’ve walked through an end-to-end example that demonstrates how to pass a function (with or without parameters) from a parent widget to a child widget. If you’d like to explore more exciting and new things about Flutter, take a look at the following articles:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Advertisements

Related Articles

Latest Articles