Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save slightfoot/b8ddae84cdad38fc4db75aed45538ebc to your computer and use it in GitHub Desktop.
Save slightfoot/b8ddae84cdad38fc4db75aed45538ebc to your computer and use it in GitHub Desktop.
Null callback shortcut?

Stumbled upon this, the code at the bottom compiles, but there is no output, when I was thinking it might output something like >> list 123, 456

Was looking for a shorthand to

final cb = callback;
if (cb != null) {
  cb(['123','456']);
}

I know I can use callback!(['123','456']) inside conditional, but I would have expected callback?(['123','456']) would also compile, but it doesn't.

callback?.call(['123','456']);

Any chance there is a way to make it work as I guessed?

import 'package:test/test.dart';

typedef RegisteredClientListCallback = void Function(List<String> clientIds);
main() {
  RegisteredClientListCallback? callback = (clientIds) => print('list $clientIds');
  test('description', () {
    callback ??
        (params) {
          //...
        }(['123', '456']);
  });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment