Null check operator used on a null value

1 Min Read

In Dart, you can use the null check operator ?? to provide a default value in case a given value is null. However, if you use the null check operator on a null value, it will result in a runtime error.

To avoid this error, you need to make sure that the value being checked is not null before using the null check operator. Here’s an example of how to perform a null check in Dart:

String name;
String displayName = name ?? 'Guest';

In this example, name is initialized as null, so displayName will be assigned the value 'Guest', which is the default value provided after the ?? operator.

If you want to check multiple values for null before using the null check operator, you can use the following code:

String name;
String lastName;
String fullName = (name ?? '') + ' ' + (lastName ?? '');

In this example, both name and lastName are checked for null before being concatenated to form fullName. If either name or lastName is null, it will be replaced with an empty string before being concatenated.

Share this Article
Leave a comment