79556584

Date: 2025-04-05 05:28:24
Score: 1
Natty:
Report link

Problem :

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


✅ Fix

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'); }

Reference

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • User mentioned (1): @override
  • User mentioned (0): @override
  • User mentioned (0): @override
  • Low reputation (1):
Posted by: Sahad Kachhawala