How to Show or Hide Widgets Programmatically in Flutter?

Flutter SDK is an open-source software development kit developed by Google. It allows developers to build cross-platform apps for Android and IOS. Dart programming language, which has easy-to-learn and powerful features such as Hot Reload. 


In this article visibility of widgets programmatically in the Flutter mobile application.

We will use the visibility widget in mobile applications. For example, mobile screen click on the button then the image hides and unhides on the  mobile application.

Syntax : 

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

Here is the step by step Implementation process:

Step 1:Create a new project in the Flutter project or you can use an already created Flutter project.
     
Step 2: Below code write in Homescreen.dart in lib folder.
 import 'package:flutter/material.dart';

void main()
{
runApp(HomeScreen());
}
class HomeScreen extends StatelessWidget {
const HomeScreen({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;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(" Toggle Demo"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// The widget whose visibility we want to change
Visibility(
visible: _isVisible,
child: Image.asset('assets/images/company_logo.png'),
),
const SizedBox(height: 20),
// The button that will toggle the visibility of the widget
ElevatedButton(
onPressed: () {
setState(() {
_isVisible = !_isVisible;
});
},
child: const Text('Toggle of Image'),
),
],
),
),
);
}
}

 

Step 3: Output of above example

Happy coding!
365Bloggy May 28, 2024
Share this post
Tags
SUBSCRIBE THIS FORM


Archive