将回调方法作为参数发送

huangapple go评论59阅读模式
英文:

Send call back method as parameter

问题

我有一个Dart类,其中有一个用于显示警报的辅助方法。该警报在应用程序中多次显示,但是在不同位置上的警报上的onPressed()执行不同的操作。我想将我希望onPressed()执行的操作作为参数传递。

这是我的辅助方法:

basicAlertWithOkWithCallback(String message, BuildContext context, void Function() f){
    
  showDialog(
    context: context,
    builder: (context) =>
        AlertDialog(
          content: Text(message),
          actions: <Widget>[
            TextButton(
              child: const Text('OK'),
              onPressed: () async {
                f();
              },
            ),
          ],
        ),
  );
}

我从另一个屏幕这样调用该方法:

basicAlertWithOkWithCallback('Session successfully saved.', context, callBack(context));

并且在该屏幕上,我创建了以下方法,当按下OK按钮时我希望执行它:

callBack(BuildContext context){
  print('CALLED');
  Navigator.of(context).pop();
  Navigator.of(context).pop();
  Navigator.of(context).pop();
}

问题是,这个方法在警报显示后立即被调用,甚至在用户按下OK按钮之前就被调用。为什么会立即调用,而不是在onPressed()中调用?

英文:

I have a Dart class where I have a helper method for displaying an Alert. The alert is shown many times on the app, but the onPressed() on the alert does different things in different places. I want to send as a parameter, what I want the onPressed() to do.

Here is my helper method:

basicAlertWithOkWithCallback(String message, BuildContext context, void Function() f){

  showDialog(
    context: context,
    builder: (context) =&gt;
        AlertDialog(
          content: Text(message),
          actions: &lt;Widget&gt;[
            TextButton(
              child: const Text(&#39;OK&#39;),
              onPressed: () async {
                f;
              },
            ),
          ],
        ),
  );
}

I call the method from another screen like this:

basicAlertWithOkWithCallback('Session sucessfully saved.', context, callBack(context));

And on that screen I made this method, which I want to execute when OK is pressed:

callBack(BuildContext context){
  print(&#39;CALLED&#39;);
  Navigator.of(context).pop();
  Navigator.of(context).pop();
  Navigator.of(context).pop();
}

The problem is, this method gets called straight away when the alert is displayed, even before the user presses on OK. Why is it called right away, and not on the onPressed()

答案1

得分: 2

callBack方法在调用basicAlertWithOkWithCallback时立即被调用的原因是因为你在调用basicAlertWithOkWithCallback方法时调用了callBack方法并将其返回值作为参数传递给basicAlertWithOkWithCallback方法,而不是直接传递callBack方法本身。

要解决这个问题,你需要像这样将callBack方法作为参数传递给basicAlertWithOkWithCallback方法:

basicAlertWithOkWithCallback('Session successfully saved.', context, callBack);

请注意,在上述代码中我们没有使用()调用callBack方法。相反,我们传递了对callBack方法的引用,以便在用户按下'OK'按钮时稍后调用它。

此外,你需要通过在onPressed回调的f参数后添加()来调用onPressed回调中的f函数,像这样:

onPressed: () async 
{
  f();
},
通过这样做callBack方法只会在用户按下'OK'按钮时调用

<details>
<summary>英文:</summary>

The reason why callBack method is called immediately when basicAlertWithOkWithCallback is called is because you are invoking the callBack method and passing its return value as a parameter to basicAlertWithOkWithCallback method, instead of passing the callBack method itself.

To fix this, you need to pass the callBack method as a parameter to basicAlertWithOkWithCallback method like this:

    basicAlertWithOkWithCallback(&#39;Session successfully saved.&#39;, context, callBack);

Notice that we are not invoking the callBack method with () in the above code. Instead, we are passing a reference to the callBack method, so that it can be invoked later when the user presses the &#39;OK&#39; button.

Also, you need to invoke the f function inside the onPressed callback by adding () after the f parameter like this:

    onPressed: () async 
    {
      f();
    },
By doing this, the callBack method will only be called when the user presses the &#39;OK&#39; button.


</details>



# 答案2
**得分**: 0

```dart
class SomeWidget extends StatelessWidget {
  const SomeWidget({Key? key, required this.ontap}) : super(key: key);

  final VoidCallback ontap;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: ontap,
      child: Container(),
    );
  }
}


// call it like this
SomeWidget(ontap: (){})
英文:
class SomeWidget extends StatelessWidget {
  const SomeWidget({Key? key, required this.ontap}) : super(key: key);

  final VoidCallback ontap;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: ontap,
      child: Container(),
    );
  }
}


// call it like this
SomeWidget(ontap: (){})

huangapple
  • 本文由 发表于 2023年2月24日 04:00:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75549751.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定