Null Safety Practice Questions in Dart

  1. Create a function that takes a nullable String and returns its length. If the string is null, return 0.
  2. Write a Dart program that demonstrates the use of the null assertion operator (!) on a nullable variable.
  3. Create a class Person with a nullable property age. Write a method that returns "Adult" if the age is greater than or equal to 18, otherwise return "Minor".
  4. Implement a function that takes a nullable list of integers and returns the sum of all its elements. If the list is null, return 0.
  5. Write a program that demonstrates the use of the null coalescing operator (??) to provide a default value for a nullable variable.
  6. Create a method that accepts a nullable parameter and prints a message. If the parameter is null, print "No value provided".
  7. Implement a class Book with a nullable String property title. Write a method that returns the title or a default message if the title is null.
  8. Create a function that uses the null aware access operator (?.) to safely call a method on a nullable object.
  9. Write a program that initializes a late variable and accesses it. Ensure that you handle potential initialization errors.
  10. Create a class User with a nullable String property username. Write a method that returns a greeting message, using a default name if the username is null.

 Solution with Explanations

  1. Function to Return Length of a Nullable String

    int getStringLength(String? str) {
      return str?.length ?? 0;
    }
    

    Explanation: The function checks if str is null. If it is, the null coalescing operator (??) returns 0. Otherwise, it returns the length of the string.

  2. Using the Null Assertion Operator

    void main() {
      String? nullableString = 'Hello, Dart!';
      print(nullableString!); // Output: Hello, Dart!
       }
    

    Explanation: The ! operator is used to assert that nullableString is not null. If it were null, it would throw a LateInitializationError.

  3. Person Class with Nullable Age

    class Person {
      int? age;
    
      String checkAge() {
        return (age != null && age! >= 18) ? 'Adult' : 'Minor';
      }
    }
    

    Explanation: The method checkAge uses a null check and the null assertion operator (!) to safely access age. It returns "Adult" or "Minor" based on the age value.

  4. Sum of Nullable List of Integers

    int sumNullableList(List<int>? numbers) {
      return numbers?.reduce((a, b) => a + b) ?? 0;
    }
    

    Explanation: This function checks if numbers is null. If it is not, it uses reduce to sum the list. If it is null, it returns 0.

  5. Using the Null Coalescing Operator

    void main() {
      String? name;
      String displayName = name ?? 'Guest';
      print(displayName); // Output: Guest 
      }
    

    Explanation: The null coalescing operator (??) provides a default value of 'Guest' when name is null.

  6. Method with Nullable Parameter

    void printMessage(String? message) {
      print(message ?? 'No value provided');
    }
    

    Explanation: The method checks if message is null. If it is, it prints the default message instead.

  7. Book Class with Nullable Title

    class Book {
      String? title;
    
      String getTitle() {
        return title ?? 'No Title';
      }
    }
    

    Explanation: The getTitle method uses the null coalescing operator to return the title or a default message if the title is null.

  8. Using Null Aware Access Operator

    class Car {
      void start() {
        print('Car started');
      }
    }
    
    void main() {
      Car? myCar;
      myCar?.start(); // No error, does nothing since myCar is null 
      }
    

    Explanation: The ?. operator safely calls the start method on myCar. If myCar is null, the method call is skipped without throwing an error.

  9. Late Variable Initialization

    late String description;
    
    void initializeDescription() {
      description = 'This is a late variable.';
    }
    
    void main() {
      initializeDescription();
      print(description); // Output: This is a late variable. 
      }
    

    Explanation: The late keyword allows description to be initialized later. If accessed before initialization, it would throw a LateInitializationError.

  10. User Class with Nullable Username

    class User {
      String? username;
    
      String greet() {
        return 'Hello, ${username ?? 'Guest'}!';
      }
    }
    

    Explanation: The greet method uses the null coalescing operator to provide a default name if username is null, ensuring a friendly greeting is always returned.

PLAY QUIZ

What does the getStringLength function return if the input string is null?

The length of the string

An exception

0

A default string