Function as parameter in widget flutter

600

Replace your _Btn with the following:

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,
      ),
    );
  }
}

Now, use it like this:

_Btn(
  name: _btnOne,
  btn: () => onClick(1),
)
Share:
600
Coder123
Author by

Coder123

Updated on December 28, 2022

Comments

  • Coder123
    Coder123 over 1 year

    I am trying to pass function as a parameter in my custom widget:

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

    I made an onClick function in my main widget:

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

    and my button widget:

    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();
            },
          ),
        );
      }
    }
    

    I am new to flutter, and I am not sure why its not working, if I am doing the next syntax than its ok:

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

    thanks

    • Simon Sot
      Simon Sot about 3 years
      Pass argument to function when you invoke it, not when you pass it down, delete (1) in dependency injection and pass 1 in onPressed
  • Coder123
    Coder123 about 3 years
    because the method is not defined for the btn widget
  • Coder123
    Coder123 about 3 years
    do you mean to remove the brackets?
  • CopsOnRoad
    CopsOnRoad about 3 years
    There are many things I changed to make it work, can you use the entire code I posted and not just one thing.