Home > Software design >  Callback called immediately when passing it to a button widget
Callback called immediately when passing it to a button widget

Time:11-02

I'm trying to pass a function that takes a parameter to a widget, which will then be called when the button is pressed. Except the function is executed as soon as the button is built. I thought by omitting the parentheses I should be able to prevent this.

Another clue that might help solve the answer is that the button appears disabled as if the onPressed has a null value.

Can someone explain why this code has this behaviour?

Thanks.

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({Key? key}) : super(key: key);
    
      printString(String myString) {
        print(myString);
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: Scaffold(
            body: MyButton(
              onPressed: printString,
              message: 'Hello World',
            ),
          ),
        );
      }
    }
    
    class MyButton extends StatelessWidget {
      final Function(String) onPressed;
      final String message;
    
      const MyButton({required this.onPressed, required this.message});
    
      @override
      Widget build(BuildContext context) {
        return ElevatedButton(
          onPressed: onPressed(message),
          child: const Text('Press Here'),
        );
      }
    }

CodePudding user response:

Refer to this answer for further explanation.

Then change:

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      // onPressed: onPressed(message),
      onPressed: () => onPressed(message),
      child: const Text('Press Here'),
    );
  }

CodePudding user response:

You're callback parameter is executing the function instead of passing in a function. Change the callback parameter to:

onPressed: () => onPressed(message),
  • Related