What is the purpose of the Visibility widget in Flutter?
#widget#visibility#ui
Answer
Overview
The 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.textVisibility
Basic Usage
dartbool _isVisible = true; Visibility( visible: _isVisible, child: Text('I can be hidden!'), )
Visibility vs Opacity vs if/else
| Approach | Space Preserved | Widget Active | Performance |
|---|---|---|---|
text | ✅ Yes (default) | ❌ No | ✅ Good |
text | ✅ Yes | ✅ Yes (still receives touches) | ⚠️ Moderate |
text | ❌ No (removed) | ❌ No | ✅ Best (widget removed) |
text | ❌ No | ❌ No | ✅ Good |
Key Parameters
dartVisibility( 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
when you want to keep a widget's space. UsetextVisibilityto fully remove it from the tree.textif (condition)