Coder123
Coder123

Reputation: 854

Function as parameter in widget flutter

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

Upvotes: 1

Views: 1199

Answers (2)

viniciusbaca
viniciusbaca

Reputation: 306

Why not send the function parameter as a parameter then call onClick(parameter) inside?

Like this:

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

Upvotes: 0

CopsOnRoad
CopsOnRoad

Reputation: 268314

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

Upvotes: 1

Related Questions