Null Safety Practice Questions in Dart
- Create a function that takes a nullable
Stringand returns its length. If the string is null, return 0. - Write a Dart program that demonstrates the use of the null assertion operator (
!) on a nullable variable. - Create a class
Personwith a nullable propertyage. Write a method that returns "Adult" if the age is greater than or equal to 18, otherwise return "Minor". - 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.
- Write a program that demonstrates the use of the null coalescing operator (
??) to provide a default value for a nullable variable. - Create a method that accepts a nullable parameter and prints a message. If the parameter is null, print "No value provided".
- Implement a class
Bookwith a nullableStringpropertytitle. Write a method that returns the title or a default message if the title is null. - Create a function that uses the null aware access operator (
?.) to safely call a method on a nullable object. - Write a program that initializes a late variable and accesses it. Ensure that you handle potential initialization errors.
- Create a class
Userwith a nullableStringpropertyusername. Write a method that returns a greeting message, using a default name if the username is null.
Solution with Explanations
Function to Return Length of a Nullable String
int getStringLength(String? str) { return str?.length ?? 0; }Explanation: The function checks if
stris null. If it is, the null coalescing operator (??) returns 0. Otherwise, it returns the length of the string.Using the Null Assertion Operator
void main() { String? nullableString = 'Hello, Dart!'; print(nullableString!); // Output: Hello, Dart! }Explanation: The
!operator is used to assert thatnullableStringis not null. If it were null, it would throw aLateInitializationError.Person Class with Nullable Age
class Person { int? age; String checkAge() { return (age != null && age! >= 18) ? 'Adult' : 'Minor'; } }Explanation: The method
checkAgeuses a null check and the null assertion operator (!) to safely accessage. It returns "Adult" or "Minor" based on the age value.Sum of Nullable List of Integers
int sumNullableList(List<int>? numbers) { return numbers?.reduce((a, b) => a + b) ?? 0; }Explanation: This function checks if
numbersis null. If it is not, it usesreduceto sum the list. If it is null, it returns 0.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' whennameis null.Method with Nullable Parameter
void printMessage(String? message) { print(message ?? 'No value provided'); }Explanation: The method checks if
messageis null. If it is, it prints the default message instead.Book Class with Nullable Title
class Book { String? title; String getTitle() { return title ?? 'No Title'; } }Explanation: The
getTitlemethod uses the null coalescing operator to return the title or a default message if the title is null.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 thestartmethod onmyCar. IfmyCaris null, the method call is skipped without throwing an error.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
latekeyword allowsdescriptionto be initialized later. If accessed before initialization, it would throw aLateInitializationError.User Class with Nullable Username
class User { String? username; String greet() { return 'Hello, ${username ?? 'Guest'}!'; } }Explanation: The
greetmethod uses the null coalescing operator to provide a default name ifusernameis null, ensuring a friendly greeting is always returned.
PLAY QUIZ