Created
September 14, 2023 21:00
-
-
Save KoalityJustin/dce9863068257db2528db7c16c615f71 to your computer and use it in GitHub Desktop.
Nullable value for non-nullable function call
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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