Suppose you’re building a user profile screen, and you fetch user data from an API:
class UserProfile extends StatelessWidget {
final User? user;
const UserProfile({this.user});
@override
Widget build(BuildContext context) {
return Text(user.name); // NoSuchMethodError if user is null
}
}
CopyEdit
class UserProfile extends StatelessWidget { final User? user; const UserProfile({this.user}); @override Widget build(BuildContext context) { return Text(user.name); // NoSuchMethodError if user is null } }
If user
is null
, calling .name
will throw:
NoSuchMethodError: The method 'name' was called on null.
Receiver: null
Tried calling: name
CopyEdit
NoSuchMethodError: The method 'name' was called on null. Receiver: null Tried calling: name
Option 1: Add a null check
@override
Widget build(BuildContext context) {
if (user == null) {
return Text('Loading...');
}
return Text(user!.name);
}
CopyEdit
@override Widget build(BuildContext context) { if (user == null) { return Text('Loading...'); } return Text(user!.name); }
Option 2: Use null-aware operator
@override
Widget build(BuildContext context) {
return Text(user?.name ?? 'Guest User');
}
CopyEdit
@override Widget build(BuildContext context) { return Text(user?.name ?? 'Guest User'); }