Flutter - 同时执行两个函数,一个通过构造函数,一个从 class 内部同时执行

Flutter - Execute two Functions, one via a constructor and one from inside a class at the same time

在学习Futter的过程中,我运行遇到了一个问题,如何同时执行两个函数。一个函数来自 Button Class 中的构造函数以及 Button class.

中的另一个函数

这是示例代码:

import 'package:flutter/material.dart';

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

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Container(
          color: Colors.blueGrey,
          child: Center(
            child: Button(
              whenButtonPressed: () {
                print("Button pressed from outside the Button Class");
              },
            ),
          ),
        ),
      ),
    );
  }
}

class Button extends StatelessWidget {
  const Button({this.whenButtonPressed, Key? key}) : super(key: key);

  final VoidCallback? whenButtonPressed;

  @override
  Widget build(BuildContext context) {
    return FloatingActionButton(
      onPressed: whenButtonPressed,
                 //print("Button pressed from inside the Button Class"); <- Execute this additionally. 
      backgroundColor: Colors.red,
    );
  }
}

我已经尝试将 onPressed 和其他打印语句放在大括号中。但随后仅执行打印语句“从 Button Class 内部按下按钮”,而不执行 whenButtonPressed 函数。这种行为的原因是什么?我该如何正确编写?

class Button extends StatelessWidget {
  const Button({this.whenButtonPressed, Key? key}) : super(key: key);

  final VoidCallback? whenButtonPressed;

  @override
  Widget build(BuildContext context) {
    return FloatingActionButton(
      onPressed: (){ whenButtonPressed; // <-now this is not executed. 
                 print("Button pressed from inside the Button Class");},

      backgroundColor: Colors.red,
    );
  }
}

正如@Peter Koltai 在他的解决方案中所述,您必须将 () 添加到 whenButtonPressed -> whenButtonPressed()。 使这项工作正确的代码是:

class Button extends StatelessWidget {
  const Button({this.whenButtonPressed, Key? key}) : super(key: key);

  final VoidCallback? whenButtonPressed;

  @override
  Widget build(BuildContext context) {
    return FloatingActionButton(
      onPressed: () {
        whenButtonPressed!();
        print("Button pressed from inside the Button Class");
      },
      backgroundColor: Colors.red,
    );
  }
}