'How to pass a function through the constructor of a class?

I would like to pass a function through the constructor of a class. but when i call it, nothing happening. debug write: func : {_Closure}

import 'package:flutter/material.dart';

    void main() {
      runApp(Myclass(func: myfunction()));
    }

    class Myclass extends StatelessWidget {

      final Function func;
      Myclass({@required this.func});

      @override
      Widget build(BuildContext context) {
      /* some code here */

      this.func(); // <----- don't call myfunction() ! :( 

      }
    }

    myfunction()
    {
      /* some code here */
    }

Thank you for the help



Solution 1:[1]

You don't passing your function in method, just its result. Check this line:

runApp(Myclass(func: myfunction()));

Using brackets you tell your program "do myfunction, return the result and put it in args". just use myfunction without brackets like that:

 runApp(Myclass(func: myfunction));

Solution 2:[2]

Try this.

  class CsCommonButtonWidget extends StatefulWidget {
  const CsCommonButtonWidget(
      {required this.onPressed,
      required this.titleText,
      this.titleTextAlign = TextAlign.center});

  final Function? onPressed;
  final String titleText;
  final TextAlign titleTextAlign;

  @override
  _CsCommonButtonWidgetState createState() => _CsCommonButtonWidgetState();
}

class _CsCommonButtonWidgetState extends State<CsCommonButtonWidget> {
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(
          primary: Colors.red, padding: const EdgeInsets.all(CsDimens.SPACE16)),
      child: Text(widget.titleText,style: TextStyle(fontSize: CsDimens.SPACE14),),
      onPressed: () {
        widget.onPressed!();
      },
    );
  }
}

Usage

CsCommonButtonWidget(
                    onPressed: () {
                      print("Login clicked");
                    },
                    titleText: "Login"),

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 alordead
Solution 2 Quick learner