作为小部件颤振中的参数的功能

时间:2021-04-01 15:01:30

标签: function flutter

我试图在我的自定义小部件中将函数作为参数传递:

_Btn(name: _btnOne, continueBtn: onClick(1)),

我在主小部件中创建了一个 onClick 函数:

onClick(int i) {
    switch(i){
      case 1:{ 
        print('hello');
      }
        break;
  }
}

和我的按钮小部件:

class _Btn extends StatelessWidget {
  final Function btn;

  const _GreenBtn({
    Key key,
    this.btn
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: ElevatedButton(
        child: Text('hello'),
        style: ElevatedButton.styleFrom(
          primary: Colors.white,
        ),
        onPressed: () {
          btn();
        },
      ),
    );
  }
}

我是 flutter 的新手,我不知道为什么它不起作用, 如果我正在做下一个语法而不是它:

_Btn(name: _btnOne, continueBtn: () => print('hello')),

谢谢

2 个答案:

答案 0 :(得分:0)

将您的 _Btn 替换为以下内容:

class _Btn extends StatelessWidget {
  final Function btn;
  final String name;
  const _Btn({Key key, this.btn, this.name}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: ElevatedButton(
        child: Text('hello'),
        style: ElevatedButton.styleFrom(primary: Colors.white),
        onPressed: btn,
      ),
    );
  }
}

现在,像这样使用它:

_Btn(
  name: _btnOne,
  btn: () => onClick(1),
)

答案 1 :(得分:0)

为什么不把函数参数作为参数发送然后在里面调用onClick(parameter)?

像这样:

class _Btn extends StatelessWidget {
  final int i;

  const _GreenBtn({
    Key key,
    this.btn
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: ElevatedButton(
        child: Text('hello'),
        style: ElevatedButton.styleFrom(
          primary: Colors.white,
        ),
        onPressed: () {
          onClick(i) //here
        },
      ),
    );
  }
}