Flutter – Show/hide widgets programmatically

Flutter – Many times developers want to hide/show widgets depending upon conditions in the flutter applications. Using the Visibility Widget, we can easily archive the functionality. The Visibility widget is the best widget for hiding and showing widgets rather than the opacity widgets.

In this tutorial, you will learn How to show/hide widgets programmatically.

Show/Hide Widgets Programatically

Wrap the widget with the Visibility widget, if you want to hide it.

For example,

bool _isVisible = true;
Code language: JavaScript (javascript)
Visibility( visible: _isVisible, child: Image.asset("assets/icon/icon.png"), ),
Code language: JavaScript (javascript)

In the visible property, you can give your own condition that must return a boolean value.

Full source code of this example,

import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) => MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), ); } class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { bool _isVisible = true; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Show/hide Widget"), ), body: Center( child: Visibility( visible: _isVisible, child: Image.asset("assets/icon/icon.png"), ), ), floatingActionButton: FloatingActionButton( onPressed: () { setState(() { _isVisible = !_isVisible; }); }, child: Text(_isVisible ? "Hide" : "Show"), ), ); } }
Code language: PHP (php)

Also read, How to add a border to a widget in the flutter.