Visibility Widget Flutter: How It Works and When to Use
Visibility widget in Flutter controls whether a child widget is visible or hidden in the UI. It can show or hide the widget while optionally keeping its space reserved or removing it completely from the layout.How It Works
The Visibility widget acts like a light switch for any widget inside it. When you turn it "on" by setting visible: true, the child widget appears on the screen as usual. When you turn it "off" by setting visible: false, you can choose if the widget disappears completely or just becomes invisible but still takes up space.
Think of it like a window with blinds: you can open the blinds to see outside (widget visible), close them but keep the window frame (widget invisible but space kept), or remove the window entirely (widget hidden and space removed). This flexibility helps keep your app layout neat and predictable.
Example
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatefulWidget { const MyApp({super.key}); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { bool isVisible = true; @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Visibility Widget Example')), body: Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ Visibility( visible: isVisible, child: const Text('Hello, I am visible!'), ), const SizedBox(height: 20), ElevatedButton( onPressed: () { setState(() { isVisible = !isVisible; }); }, child: const Text('Toggle Visibility'), ), ], ), ), ), ); } }
When to Use
Use the Visibility widget when you want to show or hide parts of your UI dynamically without rebuilding the whole screen. It is helpful for:
- Showing error messages only when needed.
- Hiding buttons or controls based on user actions.
- Keeping layout space reserved to avoid UI jumps when widgets appear or disappear.
For example, in a form, you might hide optional fields until the user selects a checkbox. Using Visibility keeps your UI smooth and predictable.
Key Points
- visible: Controls if the child is shown or hidden.
- maintainSize, maintainAnimation, maintainState: Options to keep the widget's space and state even when hidden.
- Helps avoid layout shifts by reserving space.
- Useful for conditional UI elements without removing them from the widget tree.