簡體   English   中英

Function 作為小部件 flutter 中的參數

[英]Function as parameter in widget flutter

我正在嘗試將 function 作為自定義小部件中的參數傳遞:

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

我在我的主要小部件中制作了 onClick function :

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')),

謝謝

將您的_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),
)

為什么不發送 function 參數作為參數然后在里面調用 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
        },
      ),
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM