Flutter: Can I pass arguments to a function defined in an onPress event on a button?

后端 未结 5 790
北荒
北荒 2021-02-18 20:04

I have a simple form with a button to calculate the form. I figure it\'s better to hit the button to start the action of calculating and pass the variables to the dumb function

相关标签:
5条回答
  • 2021-02-18 20:45

    Shorthand function designed in such a way that it is allowed to return function with type void as mentioned in this article --> So why is returning everything allowed through a shorthand function[()=>] even if the return type is void?

    So that you have two approaches in your disposal:

    use

    onPressed: () => calculate(1, 2),
    

    or

    onPressed: (){calculate(1, 2);},
    
    0 讨论(0)
  • 2021-02-18 20:54

    Do you remember the very first line in flutter which is

    void main() => runApp(MyApp());
    

    Where => represents one line functions or methods which is key while calling functions with arguments.

    Ex:

    void display() {
    
    }
    

    we can call the above function by

    IconButton(icon: Icon(Icons.add), onPressed: display)
    

    here we can not include () with display

    But, when there is one or more than one arguments to be passed then it goes like below

    void addition(int value1, int value2) {
        value1 + value2
    }
    
    IconButton(icon: Icon(Icons.add), onPressed: ()=>addition(2, 4))
    
    0 讨论(0)
  • 2021-02-18 21:08

    Use

    onPressed: (){calculate(1, 2);},
    
    0 讨论(0)
  • 2021-02-18 21:09

    e.g.

        int  result = 0;
    
        void calculate(num1, num2) {
         setState(() {
             result = num1 + num2;
         });
        }
    
    
        new RaisedButton(
              onPressed: () => calculate(1, 100),
              ...
        ),
        new Text("$result")
    
    0 讨论(0)
  • 2021-02-18 21:09

    Just found the answer. No. According to the onPressed property of the RaisedButton class, the onPressed property has a type of VoidCallback, which return void and according to the docs VoidCallBack is the Signature of callbacks that have no arguments and return no data.

    Edit: Thanks guys. To solve this, you use an anonymous function, like so

    (){your code here}

    0 讨论(0)
提交回复
热议问题