How to ensure user does not pass null variable to Flutter plugin?

Issue

Let’s say, in Dart/Flutter you are designing a plugin API have a function like this:

static Future<void> startPlaying(Uint8List bytes) async {
    _channel.invokeMethod('playBytes', bytes);
}

Would it be true to say that, thanks to the null-safety feature of Dart, we are not responsible in the event that the ‘bytes’ parameter is passed in as null by the plugin user (and thus causing a runtime crash) because in order to do so, they would have to explicitly unwrap a nullable variable, thereby promising that it is is not null.

OR… is there some other thing we should do such as throwing an exception?

Solution

With sound null safety, there is no way to call that method with null as argument.

With unsound null safety, which is what you get if not every library of your program is opted into null safety, it’s technically possible to pass null as an argument (because a non-null safe library could be doing the calling, or could be passing null into other null safe code, which doesn’t check because it assumes null safety.)

You can choose to check the value coming in, as an extra precaution.
The language makes that hard for you, because locally the code looks null safe.
Something like

if (bytes as dynamic == null) throw ArgumentError.notNull("bytes");

I personally wouldn’t bother with that, unless there is a real risk of something going spectacularly wrong if null manages to get into the code.
It’s documented as not allowing a null value, and most well-behaved code will respect that. Eventually, when all programs are soundly null safe, that check would just be dead code.

Answered By – lrn

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *