Question #324EasyWidgets & UI

What is the purpose of the Visibility widget in Flutter?

#widget#visibility#ui

Answer

Overview

The

text
Visibility
widget shows or hides its child widget based on a boolean condition, with fine-grained control over how the hidden widget is treated in the layout.


Basic Usage

dart
bool _isVisible = true;

Visibility(
  visible: _isVisible,
  child: Text('I can be hidden!'),
)

Visibility vs Opacity vs if/else

ApproachSpace PreservedWidget ActivePerformance
text
Visibility(visible: false)
✅ Yes (default)❌ No✅ Good
text
Opacity(opacity: 0)
✅ Yes✅ Yes (still receives touches)⚠️ Moderate
text
if (condition) Widget()
❌ No (removed)❌ No✅ Best (widget removed)
text
Visibility(maintainSize: false)
❌ No❌ No✅ Good

Key Parameters

dart
Visibility(
  visible: false,          // hide the child
  maintainSize: true,      // keep the space
  maintainAnimation: true, // keep animations running
  maintainState: true,     // keep widget state
  replacement: SizedBox(), // what to show when hidden
  child: MyWidget(),
)

Common Patterns

dart
// Toggle visibility keeping layout space
Visibility(
  visible: _showLabel,
  maintainSize: true,
  maintainAnimation: true,
  maintainState: true,
  child: Text('Optional Label'),
)

// Remove completely from layout (same as if/else)
Visibility(
  visible: _showButton,
  child: ElevatedButton(onPressed: () {}, child: Text('Submit')),
)

// Show a placeholder when hidden
Visibility(
  visible: _isLoaded,
  replacement: CircularProgressIndicator(),
  child: DataWidget(),
)

Quick Rule: Use

text
Visibility
when you want to keep a widget's space. Use
text
if (condition)
to fully remove it from the tree.