Bird
Raised Fist0
Fluttermobile~20 mins

Null safety in Flutter - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Null Safety Demo
This screen demonstrates how to safely handle nullable and non-nullable variables in Flutter using null safety features.
Target UI
-------------------------
| Null Safety Demo      |
|-----------------------|
| Name: [___________]   |
|                       |
| Greeting:             |
|                       |
| [Show Greeting Button]|
-------------------------
Add a TextField to enter a name (nullable String).
Add a button labeled 'Show Greeting'.
When the button is pressed, display a greeting message below.
If the name is null or empty, show 'Hello, Guest!' instead.
Use null safety features to avoid runtime errors.
Starter Code
Flutter
import 'package:flutter/material.dart';

class NullSafetyDemo extends StatefulWidget {
  @override
  State<NullSafetyDemo> createState() => _NullSafetyDemoState();
}

class _NullSafetyDemoState extends State<NullSafetyDemo> {
  String? name;
  String greeting = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Null Safety Demo')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextField(
              decoration: const InputDecoration(labelText: 'Name'),
              onChanged: (value) {
                // TODO: Update name variable
              },
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                // TODO: Update greeting using null safety
              },
              child: const Text('Show Greeting'),
            ),
            const SizedBox(height: 20),
            Text(greeting, style: const TextStyle(fontSize: 18)),
          ],
        ),
      ),
    );
  }
}
Task 1
Task 2
Task 3
Task 4
Task 5
Solution
Flutter
import 'package:flutter/material.dart';

class NullSafetyDemo extends StatefulWidget {
  @override
  State<NullSafetyDemo> createState() => _NullSafetyDemoState();
}

class _NullSafetyDemoState extends State<NullSafetyDemo> {
  String? name;
  String greeting = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Null Safety Demo')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextField(
              decoration: const InputDecoration(labelText: 'Name'),
              onChanged: (value) {
                setState(() {
                  name = value.isEmpty ? null : value;
                });
              },
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  greeting = (name == null || name!.isEmpty) ? 'Hello, Guest!' : 'Hello, $name!';
                });
              },
              child: const Text('Show Greeting'),
            ),
            const SizedBox(height: 20),
            Text(greeting, style: const TextStyle(fontSize: 18)),
          ],
        ),
      ),
    );
  }
}

This app uses Flutter's null safety to handle a nullable String variable name. The name variable can be null if the user hasn't typed anything or cleared the input.

In the TextField, when the user types, we update name to null if the input is empty, otherwise to the typed value.

When the button is pressed, we check if name is null or empty. If so, we show a default greeting 'Hello, Guest!'. Otherwise, we greet the user by name.

Using null safety avoids runtime errors by ensuring we check for null before using the variable. The setState calls update the UI to show the greeting.

Final Result
Completed Screen
-------------------------
| Null Safety Demo      |
|-----------------------|
| Name: [Alice       ]  |
|                       |
| Greeting:             |
| Hello, Alice!         |
|                       |
| [Show Greeting Button]|
-------------------------
User types a name in the TextField.
User taps 'Show Greeting' button.
Greeting text updates to 'Hello, <name>!' if name entered.
If TextField is empty, greeting shows 'Hello, Guest!'.
Stretch Goal
Add a Clear button to reset the TextField and greeting message.
💡 Hint
Add a second ElevatedButton labeled 'Clear' that sets name to null and greeting to empty string inside setState.

Practice

(1/5)
1. What does the ? symbol mean when used after a type in Flutter null safety?
easy
A. It marks the variable as a constant.
B. It means the variable is always non-null.
C. It means the variable can hold a null value.
D. It makes the variable read-only.

Solution

  1. Step 1: Understand the ? usage in Flutter

    The ? after a type means the variable can be null, allowing it to hold either a value or null.
  2. Step 2: Compare with non-nullable types

    Without ?, variables must always have a non-null value, so ? explicitly allows null.
  3. Final Answer:

    It means the variable can hold a null value. -> Option C
  4. Quick Check:

    ? means nullable = A [OK]
Hint: Remember: ? means nullable, can hold null [OK]
Common Mistakes:
  • Thinking ? makes variable constant
  • Confusing ? with non-nullable
  • Assuming ? means read-only
2. Which of the following is the correct way to declare a nullable integer variable in Flutter?
easy
A. int? number;
B. int number?;
C. nullable int number;
D. int number = null;

Solution

  1. Step 1: Recall correct nullable syntax

    In Flutter, to declare a nullable type, place ? immediately after the type name, like int?.
  2. Step 2: Check each option

    int? number; uses int? number; which is correct. int number?; places ? after variable name, which is invalid. nullable int number; uses a non-existent keyword. int number = null; assigns null to a non-nullable type, causing error.
  3. Final Answer:

    int? number; -> Option A
  4. Quick Check:

    Nullable type syntax = int? [OK]
Hint: Put ? right after type to make nullable [OK]
Common Mistakes:
  • Placing ? after variable name
  • Using non-existent keywords like 'nullable'
  • Assigning null to non-nullable without ?
3. What will be the output of this Flutter code snippet?
int? a;
int b = a ?? 5;
print(b);
medium
A. null
B. 5
C. 0
D. Compilation error

Solution

  1. Step 1: Understand variable initialization

    Variable a is nullable and not initialized, so it is null.
  2. Step 2: Evaluate the null-coalescing operator ??

    The expression a ?? 5 means if a is null, use 5 instead.
  3. Step 3: Assign and print value

    Since a is null, b gets 5, so print(b) outputs 5.
  4. Final Answer:

    5 -> Option B
  5. Quick Check:

    ?? gives default if null = 5 [OK]
Hint: Use ?? to provide default when null [OK]
Common Mistakes:
  • Assuming uninitialized nullable is zero
  • Thinking ?? returns null
  • Expecting compilation error for nullable without init
4. Identify the error in this Flutter code snippet:
String? name;
print(name.length);
medium
A. Error: Cannot access property on nullable without check
B. No error, prints null
C. Error: Missing semicolon
D. Error: Variable 'name' not declared

Solution

  1. Step 1: Analyze nullable variable usage

    Variable name is nullable and not initialized, so it is null.
  2. Step 2: Accessing property on nullable

    Accessing name.length without null check causes error because name might be null.
  3. Step 3: Correct usage

    Use null-aware operator like name?.length or check for null before accessing.
  4. Final Answer:

    Error: Cannot access property on nullable without check -> Option A
  5. Quick Check:

    Access nullable property without check = error [OK]
Hint: Use ?. or check null before property access [OK]
Common Mistakes:
  • Assuming nullable property access is safe
  • Ignoring null checks
  • Confusing syntax errors with runtime errors
5. Given a nullable list of integers List<int>? numbers;, which code safely sums all elements or returns 0 if the list is null?
hard
A. int sum = numbers!.reduce((a, b) => a + b);
B. int sum = numbers.reduce((a, b) => a + b);
C. int sum = numbers == null ? null : numbers.reduce((a, b) => a + b);
D. int sum = numbers?.reduce((a, b) => a + b) ?? 0;

Solution

  1. Step 1: Understand nullable list and safe access

    Since numbers can be null, accessing methods directly risks error.
  2. Step 2: Analyze each option

    int sum = numbers?.reduce((a, b) => a + b) ?? 0; uses ?. to safely call reduce only if numbers is not null, then ?? 0 to default to 0 if null. int sum = numbers.reduce((a, b) => a + b); calls reduce directly, causing error if null. int sum = numbers!.reduce((a, b) => a + b); forces non-null with !, risky if null. int sum = numbers == null ? null : numbers.reduce((a, b) => a + b); returns null instead of int 0, causing type mismatch.
  3. Step 3: Choose safe and correct option

    int sum = numbers?.reduce((a, b) => a + b) ?? 0; safely sums or returns 0 if null.
  4. Final Answer:

    int sum = numbers?.reduce((a, b) => a + b) ?? 0; -> Option D
  5. Quick Check:

    Safe call + default value = int sum = numbers?.reduce((a, b) => a + b) ?? 0; [OK]
Hint: Use ?. with ?? for safe nullable operations [OK]
Common Mistakes:
  • Calling methods on nullable without safe operator
  • Using ! without null check
  • Returning null instead of default value
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard