1

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

1
  • Pass argument to function when you invoke it, not when you pass it down, delete (1) in dependency injection and pass 1 in onPressed Commented Apr 1, 2021 at 15:06

2 Answers 2

1

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),
)
Sign up to request clarification or add additional context in comments.

2 Comments

do you mean to remove the brackets?
There are many things I changed to make it work, can you use the entire code I posted and not just one thing.
0

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

1 Comment

because the method is not defined for the btn widget

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.