Skip to content

Instantly share code, notes, and snippets.

@KoalityJustin
Created September 14, 2023 21:00
Show Gist options
  • Save KoalityJustin/dce9863068257db2528db7c16c615f71 to your computer and use it in GitHub Desktop.
Save KoalityJustin/dce9863068257db2528db7c16c615f71 to your computer and use it in GitHub Desktop.
Nullable value for non-nullable function call
extension NotNullFunctionCall<T> on void Function(T) {
void maybeCall(T? value) {
if (value != null) {
return this.call(value);
}
}
}
void navigateTo(int index) {
print('The index is: $index');
}
class Example {
const Example({this.index, this.animateTo = navigateTo});
final int? index;
final void Function(int) animateTo;
void run() {
animateTo.maybeCall(index);
}
}
Future<void> main() async {
final example1 = Example(index: 0);
final example2 = Example();
example1.run(); // will print "The index is: 0"
example2.run(); // will not print anything as index is null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment