乐闻世界logo
搜索文章和话题

How to pass callback in Flutter

1个答案

1

In Flutter, passing callback functions is a common practice for enabling communication between widgets by passing and receiving events or data. Callbacks allow a parent widget to delegate specific operations to a child widget, and the child can notify the parent and provide feedback after completing the operation. Below, I'll demonstrate how to pass callbacks in Flutter using a simple example.

Step 1: Define the Child Widget

First, we define a child widget named MyButton that accepts a callback function onPressed as a required parameter, which is triggered when the button is tapped.

dart
import 'package:flutter/material.dart'; class MyButton extends StatelessWidget { final VoidCallback onPressed; MyButton({required this.onPressed}); Widget build(BuildContext context) { return ElevatedButton( onPressed: onPressed, child: Text('Click Me!'), ); } }

Step 2: Use the Child Widget in the Parent

Next, we integrate MyButton into the parent widget and pass a callback function. This callback specifies the operation the parent should execute when the button is tapped.

dart
import 'package:flutter/material.dart'; import 'my_button.dart'; // Ensure the MyButton widget is imported class HomePage extends StatelessWidget { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Callback Example'), ), body: Center( child: MyButton( onPressed: () { print('Button was clicked!'); }, ), ), ); } }

Example Analysis

In this example, MyButton is a simple custom button widget with a required onPressed parameter. This parameter is a callback function of type VoidCallback, which is invoked when the button is tapped.

Within the HomePage widget, we use MyButton and pass an anonymous function as the onPressed parameter. When the button is tapped, this anonymous function executes and prints a message to the console.

Summary

This approach enables flexible and dynamic communication between widgets in Flutter. Callbacks are not limited to basic print operations; they can be used to modify state, request data, handle form submissions, and more. Implementing callback functions is an effective strategy for decoupling components.

2024年7月19日 12:36 回复

你的答案