Flutter – Outputting Widgets Conditionally
Last Updated :
07 Apr, 2025
One of the best things about using Flutter is the control it gives you over the UI. You can easily show a loading spinner, hide buttons until a form is complete, or change views based on user selections. In this guide, we’ll cover various ways to conditionally display widgets, from simple if statements to the ternary operator and spread operator for cleaner designs.
Method 1: Using If condition
This is Flutter’s way of displaying a widget if the condition is true.
Syntax:
if (condition)
Widget()
Dart
import 'package:flutter/material.dart';
/// Entry point of the Flutter application
void main() => runApp(MyApp());
/// Root widget of the application
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'GeeksforGeeks',
/// Hides the debug banner in the top-right corner
debugShowCheckedModeBanner: false,
/// Sets the primary color theme for the app
theme: ThemeData(
primarySwatch: Colors.green,
),
/// Sets the default home page of the app
home: HomePage(),
);
}
}
/// HomePage widget that represents the main UI screen
class HomePage extends StatelessWidget {
/// A boolean flag to conditionally display widgets
final bool checked = true;
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
/// App bar with title
appBar: AppBar(
title: Text('GeeksforGeeks'),
),
/// Body of the screen with vertical layout
body: Column(
children: <Widget>[
/// Always visible text widget
Text(
'First Widget',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
/// Conditionally renders this Text widget if [checked] is true
if (checked)
Text(
'Second Widget',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
],
),
),
);
}
}
Output:
Method 2: Using Ternary operator (? : )
You may have used this operator in other languages like C++, Java, etc.
Syntax:
condition ? Widget() : OtherWidget()
# if condition is true the Widget() is displayed else OtherWidget() is displayed.
Widget and OtherWidget could be any widget even Custom.
main.dart:
Dart
import 'package:flutter/material.dart';
/// Entry point of the application
void main() => runApp(MyApp());
/// Root widget of the application
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'GeeksforGeeks',
/// Hides the debug banner in the top-right corner of the screen
debugShowCheckedModeBanner: false,
/// Sets the primary theme color of the application
theme: ThemeData(
primarySwatch: Colors.green,
),
/// Sets the HomePage as the default screen
home: HomePage(),
);
}
}
/// A stateless widget representing the home screen
class HomePage extends StatelessWidget {
/// Boolean variable used to conditionally show a widget
final bool checked = true;
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
/// App bar with title
appBar: AppBar(
title: Text('GeeksforGeeks'),
),
/// Body content arranged vertically
body: Column(
children: <Widget>[
/// Always visible text widget
Text(
'First Widget',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
/// Conditionally renders 'Second Widget' if [checked] is true,
/// otherwise renders an empty container (invisible placeholder)
checked? Text(
'Second Widget',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
)
: Container(),
],
),
),
);
}
}
Output:
Note: Instead of the ternary operator one can also use the if-else condition. This will also yield the same result.
Method 3: Custom function
If you want more control over logic, then just return a Widget. You may also use your function as well. In this method, you have total control because you are free to write as much code before displaying the code as you like. As well as you can also execute complex conditions.
main.dart:
Dart
import 'package:flutter/material.dart';
/// Entry point of the Flutter application
void main() => runApp(MyApp());
/// Root widget of the app
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'GeeksforGeeks',
// Hide the debug banner on the top right
debugShowCheckedModeBanner: false,
// Set the app's theme
theme: ThemeData(
primarySwatch: Colors.green,
),
// Set the home page of the app
home: HomePage(),
);
}
}
/// A stateless widget representing the home screen
class HomePage extends StatelessWidget {
// A boolean variable used to control conditional rendering
final checked = true;
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
/// AppBar with a title
appBar: AppBar(
title: Text('GeeksforGeeks'),
),
/// Main content of the page
body: Column(
children: <Widget>[
// A Text widget always shown
Text(
'First Widget',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
// A custom function that returns a widget
condition(),
],
),
),
);
}
/// A method that returns a widget based on a condition.
/// Uses a switch statement to decide which widget to show
Widget condition() {
// Declare a variable to hold the widget
Widget widget;
// Use a switch-case for conditional logic
// Though a simple if-else is more suitable for booleans,
// this demonstrates switch usage for clarity
switch (checked) {
case true:
widget = Text(
'Second Widget',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
);
break;
case false:
widget = Container(); // Return empty widget if condition is false
break;
default:
widget = Container(); // Default case for safety
}
// Return the appropriate widget
return widget;
}
}
Output:
Below is a Sample App to show conditional rendering for ListView as well.
Dart
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
/// Root widget of the application
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'GeeksforGeeks',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.green,
),
home: HomePage(),
);
}
}
/// StatefulWidget to toggle and show content conditionally
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
bool _selected = false;
/// Build method for the UI
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text('GeeksforGeeks'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
/// Checkbox tile with toggle logic
CheckboxListTile(
title: Text(
'Data Structures',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500),
),
value: _selected,
onChanged: (value) {
setState(() {
_selected = value ?? false;
});
},
),
SizedBox(height: 20),
/// Show content if checkbox is selected
if (_selected) ...[
Expanded(
child: ListView(
children: [
_buildTopicItem('Arrays'),
_buildTopicItem('LinkedList'),
_buildTopicItem('Stack'),
_buildTopicItem('Tree'),
],
),
),
]
],
),
),
),
);
}
/// A reusable widget to render each topic
Widget _buildTopicItem(String title) {
return Card(
elevation: 2,
margin: const EdgeInsets.symmetric(vertical: 6),
child: ListTile(
leading: Icon(Icons.bookmark),
title: Text(
title,
style: TextStyle(fontSize: 16),
),
),
);
}
}
Output:
Note: Apart from this if you want to show list items directly in the Column then you may use the following approach:
Column(
children: [
// some code
if (_selected)
...[
Text(
'Arrays',
style: TextStyle(fontSize: 16),
),
Text(
'LinkedList',
style: TextStyle(fontSize: 16),
),
Text(
'Stack',
style: TextStyle(fontSize: 16),
),
Text(
'Tree',
style: TextStyle(fontSize: 16),
)
]
// some code
]
..., //These strange three dots are spread operator.
Conditional rendering is key to creating interactive Flutter apps. It helps you manage user state, handle dynamic data, and customize layouts. Start with basics like if statements and the ternary operator, then explore custom logic and spread operators as your app evolves. With Flutter, you have the tools to build dynamic and stunning interfaces.
Similar Reads
Flutter - Folding Cell Widget
Folding Cell is the Flutter Widget that can be fold and unfold, It uses the frontWidget to show the front data, and the innerWidget to show the hidden data. Hidden is shown when the Folding cell is unfolded. When the widget is unfolded the innerWidget renders its data. When the widget is folded the
3 min read
Flutter - Splitting App into Widgets
Splitting an app into widgets refers to the breaking up of large widgets into smaller, more manageable widgets which can be inferred as smaller chunks of codes. The principal thing here is to understand when to split a widget into smaller ones. We are going to discuss when to split a widget and meth
5 min read
How to use Conditional Statement on Widget in Flutter?
Handling conditions is not too much difficult in Flutter. We can easily write our conditions based on the requirements which we are acquiring from our application. Let's work on conditions in flutter Apps. In this article, we'll talk about conditions and how we handle elements or widgets by using co
2 min read
Center widget in Flutter
Center widget comes built-in with flutter, it aligns its child widget to the center of the available space on the screen. The size of this widget will be as big as possible if the widthFactor and heightFactor properties are set to null and the dimensions are constrained. And in case the dimensions a
2 min read
Expandable Widget in Flutter
The expandable widgets do not have a fixed size, they expand on the screen according to the available areas on the screen. Due to size constraints, certain widgets can throw rendering errors, so widgets are made expandable. The one use of expandable widgets is cards that include images, texts, and t
3 min read
ClipRect Widget in Flutter
The ClipRect widget is used to clips its child using a rectangle. It associates with the Clippers family. The main use of clippers is to clip out any portion of the widget as required. It behaves similar to that of ClipRRect and is used to Clip a Rectangle portion of the child widget but without the
2 min read
endDrawer Widget in Flutter
The endDrawer is the panel displayed to the side of the body (Scaffold Widget). It is generally hidden in mobile devices. We can open it by swiping in from right to left, or we can customise it to open on-press of an icon or a button. This widget is similar to the already present Drawer widget in fl
2 min read
ClipRRect Widget in Flutter
The ClipRRect widget in flutter is used to clips its child using a rounded rectangle. It associates with the Clippers family. The main use of clippers is to clip out any portion of the widget as required. It behaves similar to that of ClipRect and is used to Clip a Rectangle portion of the child wid
2 min read
Align Widget in Flutter
Align Widget is the widget that is used to align its child within itself and optionally sizes itself based on the child's size. Align Widget is quite flexible and can change its size according to the size of its child. Constructor of Align class: Syntax: Align({Key key, AlignmentGeometry alignment:
2 min read
Flutter - Concept of Key in Widgets
In this article, we will study Keys and when and where to use them. So you may ask what are keys? Well, Keys are the ones to preserve state when widgets move around the widget tree. It is used to preserve the user scroll location or keeping state when modifying a collection. Key's aren't needed if t
5 min read