Flutter Pro Design

Small details that build taste in Flutter.

curated by Kamran BekirovKamran Bekirov

Never let users see "null"

When a field comes back null from the API and you display it with Text(state.field.toString()), user will see the word "null" sitting there on the screen. For them this means nothing.

Or the backend serializes null as the literal string "null". Same thing.

Or the field is an empty string, then there will be a blank spot where a value should be. Looks just as broken.

Text(state.field ?? '-') seems to handle these, but it misses some cases.

This extension handles all:

extension StringX on String? {
  bool get isUsable {
    return this != null && this!.isNotEmpty && this != 'null';
  }
  
  String orPlaceholder([String placeholder = '-']) {
    if (!isUsable) return placeholder;
    
    return this!;
  }
}

Now just:

Text(
  user.name.orPlaceholder(),
)
// null → "-"
  
Text(
  user.name.orPlaceholder('N/A'),
)
// null → "N/A"

Sometimes the goal isn't a placeholder, it's hiding the widget entirely. Instead of:

if (user.profession != null && user.profession!.isNotEmpty 
      && user.profession != 'null')
  Text(
    user.profession!,
  )

Just:

if (user.profession.isUsable)
  Text(
    user.profession!,
  )

When the value isn't a String, call .toString() first:

Text(
  order.totalPrice.toString().orPlaceholder(),
)

If objects in the chain can be null, wrap the whole expression in parentheses. orPlaceholder() runs on the result of the whole chain, even if something in the middle is null:

Text(
  (state.cartInfo?.totalPrice?.toString()).orPlaceholder(),
)

Without the parentheses, if cartInfo is null the expression short-circuits and orPlaceholder() never runs. The parentheses make sure it always does.

Screenshot from expen.app, made in Figma. Never got null :)