DEV Community

Cover image for Null or Nothing? Unmasking the Mystery of Parameters in Dart
Rene Lazo Mendez
Rene Lazo Mendez

Posted on • Updated on

Null or Nothing? Unmasking the Mystery of Parameters in Dart

Sometimes, in the world of development, things get a little confusing. Is a parameter null because it was explicitly passed that way, or simply because it wasn't specified? It's like trying to decipher a riddle: was it a "no" or a "don't know"?

In Dart, the distinction between a null parameter and one that hasn't been specified can be crucial. To prevent our code from turning into a soup of letters, we need a way to unmask this mystery.

Introducing the Marker Technique!

Imagine a magical object called _unspecified. This object holds no information, it merely exists to tell us that a parameter hasn't been defined. With a bit of code magic, we can use this object as a beacon to distinguish between an intentional null and a lack of information.

const Object _unspecified = Object();
Enter fullscreen mode Exit fullscreen mode

Now, let's create a function that looks for this magical object:

bool _isUnspecified(value) => identical(value, _unspecified);
Enter fullscreen mode Exit fullscreen mode

In our code, we can use this function to figure out if a parameter is null by design, or if it was simply not passed.

A Practical Example!

Let's imagine the SpaceState class. In its copyWith function, we want the successMessage and errorMessage parameters to be able to be null, but we also want the possibility for them to simply not be specified, preserving the original value.

class SpaceState {
  final bool isLoading;
  final String? successMessage;
  final String? errorMessage;

  SpaceState copyWith({
    bool? isLoading,
    Object? successMessage = _unspecified,
    Object? errorMessage = _unspecified,
  }) {
    return SpaceState(
      isLoading: isLoading ?? this.isLoading,
      successMessage: _isUnspecified(successMessage) ? this.successMessage : successMessage as String?,
      errorMessage: _isUnspecified(errorMessage) ? this.errorMessage : errorMessage as String?,
Enter fullscreen mode Exit fullscreen mode


With this approach, we can avoid errors and keep our code clean and readable. The marker technique allows us to differentiate between "null" and "not specified" with a clarity that brings us closer to achieving perfection in our code.


  • The marker technique is a creative and flexible solution, but it can also add a bit of complexity to your code.
  • It's crucial to maintain consistency in using the marker to avoid confusion and errors.

With this technique, your code will speak clearly and help you create robust and easy-to-understand applications!

Top comments (0)