0
0
Fluttermobile~20 mins

Null safety in Flutter - Mini App: Build & Ship

Choose your learning style9 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.