简体   繁体   English

如何在 Dart 中为单个变量分配两种不同的方法?

[英]How to assign two different methods to a single variable in Dart?

Minimal reproducible code:最小的可重现代码:

Future<void> foo(int i) async => print(i);
Future<void> bar(double d, bool b) async => print(b);

@override
Widget build(BuildContext context) {
  var flag = true;
  var onPressed = flag ? foo(1) : bar(0.0, true);
  return Scaffold(
    body: RaisedButton(
      onPressed: () => onPressed,
      child: Text('Button'),
    ),
  );
}

Problem:问题:

The method gets called during build process because I'm åctually calling foo(1) .该方法在构建过程中被调用,因为我实际上是在调用foo(1) How to resolve this issue?如何解决这个问题? I only want to get it done using one variable as shown above.我只想使用一个变量来完成它,如上所示。

It seems like there is no way to do this.似乎没有办法做到这一点。 The closest thing that can be done is to change my variable to a method.可以做的最接近的事情是将我的变量更改为方法。

So,所以,

Instead of代替

var onPressed = flag ? foo(1) : bar(0.0, true);

Use

void onPressed () => flag ? foo(1) : bar(0.0, true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM