aleskva
aleskva

Reputation: 1805

How to ask user for a callback function

I want to ask user for a callback function (shortened):

Future<dynamic> myfunc(dynamic onSuccess) async {
  Completer c = Completer();

  // some time-consuming procedure

  if (onSuccess is Function) {
    c.complete(true);
    return c.future.then(onSuccess());
  } else {
    c.complete(false);
    return c.future;
  }
}

bool should_be_true = await myfunc(print("Success!"))

But my code does not work, dartanalyzer throws a following error on the last line:

error • The expression here has a type of 'void', and therefore cannot be used at example/index.dart:15:35 • use_of_void_result

Upvotes: 0

Views: 221

Answers (1)

Kevin Moore
Kevin Moore

Reputation: 6161

Some comments:

  • You're passing in the result of calling print, not a function. Use () => print('...') to pass in a function.
  • In functions that return Future, you want to return ASAP so you're not blocking your caller. This is why I use scehduleMicrotask. In general, you should not need to use Completer, except for very complex async work. Try to just use async/await.
  • You don't need to flag a function using a Completer with async.

Try this:

import 'dart:async';

Future<dynamic> myfunc(dynamic onSuccess) {
  var c = Completer();

  scheduleMicrotask(() {
    // some time-consuming procedure

    if (onSuccess is Function) {
      onSuccess();
      c.complete(true);
    } else {
      c.complete(false);
    }
  });

  return c.future;
}

main() async {
  var should_be_true = await myfunc(() => print("Success!"));
}

Upvotes: 1

Related Questions