简体   繁体   中英

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) . 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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