2
votes

I just started using Flutter and I'm making a calculator. I want to set different callback methods to my buttons to perform the various operations. The thing is, I want to get the text of the clicked button to know what operation I should do, but the callback methods seem to not contain any information of the "sender widget".

In C# I can do the next, where "sender" is the button that was clicked.

var button1 = new Button();
var button2 = new Button();

public MyClassConstructor() {
    button1.Clicked += foo;
    button2.Clicked += foo;
}

public void foo (object sender, EventArgs e)
{
    var button = sender as Button;
    string id = button.ID;

    if (id == "1")
    {
        // do something
    }
    else if (id == "2")
    {
        // do something else
    }
    ...
}

Similarly, in Java, "event" contains the clicked button.

private JButton button1 = new JButton("1");
private JButton button2 = new JButton("2");

public MyClassConstructor() {
    Listener listener = new Listener();
    button1.addActionListener(listener);
    button2.addActionListener(listener);
}

private class Listener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent event) {
        if (event.getSource().equals(button1)) {
            // do something
        } else if (event.getSource().equals(button2)) {
            // do something else
        }
        ...
    }
}

Is there anything similar in Flutter? I know i can do the following:

VoidCallback foo = () {
  // do something
};

var button1 = RaisedButton(
  onPressed: foo,
  child: Text("1"),
);

var button2 = RaisedButton(
  onPressed: foo,
  child: Text("2"),
);

But the problem is that I can't get the button that was pressed because the "onPressed" definition of Flutter's RaisedButton widget is a VoidCallback, which recieves no parameters. Is there a workaround for this, or is there another way of doing it?

2

2 Answers

0
votes

But you can simple create the function and send the correct parameter as follow:
e.g.

double calculate(String operation, double val1, double val2) {
    if(operation == 'add') {
      return val1 + val2;
    }
    if(operation == 'multiply') {
      return val1 * val2;
    }
    return 0;
  }
var button1 = RaisedButton(
  onPressed: (){
       calculate('add', 3,4);
  },
  child: Text("1"),
);

var button2 = RaisedButton(
  onPressed: (){
       calculate('multiply', 3,4);
  },
  child: Text("2"),
);

See you can call whatever function you want.

0
votes

You can add a button and set the onPressed callback to call a function that collects the value pressed

 // Call back function
    onButtonPressed(int buttonValue){
    print('You clicked $buttonValue');
    // do your code here
    }

    // Button Widget
    RaisedButton(onPressed: (){
        setState(() 
             {
               onButtonPressed(1);
             });
         },child: Text('1'),),