Improve tryParse null handling

It would be better if tryParse() dealt with null better. I think it is a common requirement.

int.tryParse(null) ?? 0;

Unhandled exception:
Invalid argument(s): The source must not be null
#0      int.tryParse (dart:core-patch/dart:core/integers_patch.dart:112)
#1      main (file:///work/projects/dart/kbml_parser/main_test.dart:11:7)
#2      _startIsolate.<anonymous closure> (dart:isolate-patch/dart:isolate/isolate_patch.dart:279)
#3      _RawReceivePortImpl._handleMessage (dart:isolate-patch/dart:isolate/isolate_patch.dart:165)

dart --version
Dart VM version: 2.0.0-dev.58.0 (Unknown timestamp) on "linux_x64"

Author: Fantashit

2 thoughts on “Improve tryParse null handling

  1. Could the documentation then please be improved? Right now it reads “… returns null instead of throwing for invalid inputs.” However, in the case of the invalid input null, it still throws, which is a pitfall I learned the hard way and through finding this issue.

  2. Allowing null could improve the UX since it gives you one place to default instead of 2.

    Consider an input expression that may be null or not parseable.

    // If we allow null argument
    var result = int.tryParse(potentiallyNull()) ?? 0;

    vs

    var input = potentiallyNull();
    var result = input == null ? 0 : int.tryParse(input) ?? 0;

    or

    var result = int.tryParse(potentiallyNull() ?? '0') ?? 0;

    I can see the argument that a null input is definitely different from a non-parseable input, but it’s also annoying to need to express the default multiple times.

    In either case I’ll reopen the issue to either revisit this decision, or to fix the docs.

Comments are closed.