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.