允许将构造函数作为函数传递

时间:2019-06-10 03:55:02

标签: flutter

我想返回一个函数,如buttonText构造函数。我该如何实现?

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Button("Button", Function()),
    );
  }
}

class Button extends StatelessWidget {
  final String buttonText;

  Button(this.buttonText, this.btnFunction);

  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      onPressed: /*function()*/,
      child: Text(buttonText),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

通过您的功能

  Button("Button", (){ print("hello"); }),

或声明一个单独的函数

 void printHello(){
    print("hello");
  }

并通过

Button("Button", printHello)

在按钮类中添加Function btnFunction

class Button extends StatelessWidget {
  final String buttonText;
  final Function btnFunction;

  Button(this.buttonText, this.btnFunction);

  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      onPressed: btnFunction,
      child: Text(buttonText),
    );
  }
}