Open In App

How to Show or Hide Widgets Programmatically in Flutter?

Last Updated : 01 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Flutter SDK is an open-source software development kit developed by Google. It allows developers to build cross-platform apps for Android and iOS with a single codebase. Flutter uses the Dart programming language, which is easy to learn and has powerful features such as Hot Reload, which allows developers to see the changes they make in real-time. In this article, we will be seeing how to change the visibility of a widget programmatically in Flutter.

Approach

We will use the Visibility widget which has a property named visible that accepts a boolean value and changes the visibility of the child component based on the passes value. We do not need to add any dependency for this so we will just write the code and run the app.

Syntax:

_isVisible = false;
Visibility(
    visible: _isVisible,
    child: Image.network(url),
)

Example: The below example demonstrates the use of the Visibility widget to toggle the visibility of the Image.

Dart




import 'package:flutter/material.dart';
  
void main() {
  runApp(const MyApp());
}
  
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: MyHomePage(),
    );
  }
}
  
class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);
  
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
  
class _MyHomePageState extends State<MyHomePage> {
  bool _isVisible = true;
  final url =
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Visibility Toggle Demo"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // The widget whose visibility we want to change
            Visibility(
              visible: _isVisible,
              child: Image.network(url),
            ),
            const SizedBox(height: 20),
            // The button that will toggle the visibility of the widget
            ElevatedButton(
              onPressed: () {
                setState(() {
                  _isVisible = !_isVisible;
                });
              },
              child: const Text('Toggle Visibility of Image'),
            ),
          ],
        ),
      ),
    );
  }
}


Output:

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads