Open In App

Flutter – Outputting Widgets Conditionally

Last Updated : 26 Jan, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Flutter is Google’s UI toolkit for building beautiful, natively compiled applications for mobile, web, and desktop from a single codebase. Flutter provides various ways to display Widgets conditionally and in this article, we are going to implement all the methods.

Method 1: Using If condition

This is flutter’s way to display a widget if the condition is true.

Syntax:

if (condition) 
  Widget()

Dart




import 'package:flutter/material.dart';
  
void main() => runApp(MyApp());
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'GeeksforGeeks',
  
      // to hide debug banner
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: HomePage(),
    );
  }
}
  
class HomePage extends StatelessWidget {
  
  /// boolean variable which is [true]
  final checked = true;
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
  
        // AppBar
        appBar: AppBar(
          title: Text('GeeksforGeeks'),
        ),
        body: Column(
          children: <Widget>[
  
            // A Simple Text Widget that will be visible
            // all the time
            Text(
              'First Widget',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
  
            /// if the condition is true
            /// [condition == true] then
            /// below Text will be displayed
            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.

Dart




import 'package:flutter/material.dart';
  
void main() => runApp(MyApp());
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'GeeksforGeeks',
  
      // to hide debug banner
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: HomePage(),
    );
  }
}
  
class HomePage extends StatelessWidget {
    
/// boolean variable which is [true]
  final checked = true;
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        // AppBar
        appBar: AppBar(
          title: Text('GeeksforGeeks'),
        ),
        body: Column(
          children: <Widget>[
  
            // A Simple Text Widget that will be visible
            // all the time
            Text(
              'First Widget',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
  
            /// if the condition is true
            /// [condition == true] then
            /// below Text will be displayed
            /// else an [Empty Container] will be displayed
            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 returning a Widget. You may also use your own 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 execute complex conditions also.

Dart




import 'package:flutter/material.dart';
  
void main() => runApp(MyApp());
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'GeeksforGeeks',
  
      // to hide debug banner
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: HomePage(),
    );
  }
}
  
class HomePage extends StatelessWidget {
    
  // boolean variable which is [true]
  final checked = true;
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
          
        // AppBar
        appBar: AppBar(
          title: Text('GeeksforGeeks'),
        ),
        body: Column(
          children: <Widget>[
              
            // A Simple Text Widget that will be visible
            // all the time
            Text(
              'First Widget',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
  
            // Custom function
            condition(),
          ],
        ),
      ),
    );
  }
  
  // Function
  Widget condition() {
  
    // other logic  
    // Declare a widget variable,
    // it will be assigned later according
    // to the condition
    Widget widget;
  
    // Using switch statement to display desired
    // widget if any certain condition is met
    // You are free to use any condition
    // For simplicity I have used boolean contition
    switch (checked) {
      case true:
        widget = Text(
          'Second Widget',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        );
        break;
      case false:
        widget = Container();
        break;
      default:
        widget = Container();
    }
  
    // Finally returning a 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());
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'GeeksforGeeks',
  
      // to hide debug banner
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: HomePage(),
    );
  }
}
  
class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}
  
class _HomePageState extends State<HomePage> {
  bool _selected;
  
  @override
  void initState() {
    _selected = false;
    super.initState();
  }
  
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: Text('GeeksforGeeks'),
        ),
        body: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.symmetric(
                horizontal: 8.0,
                vertical: 16.0,
              ),
  
              /// Checkbox Widget
              child: CheckboxListTile(
                title: Text('Data Structure'),
                value: _selected,
  
                /// Toggling Checkbox value and
                /// assigning it to _selected variable
                onChanged: (value) => setState(() => _selected = value),
              ),
            ),
  
            /// if selected variable is true i.e
            /// [selected == true] then list is visible
            /// otherwise it's not
            if (_selected)
              Padding(
                padding: const EdgeInsets.symmetric(
                  horizontal: 16.0,
                  vertical: 8.0,
                ),
                child: Container(
                  height: MediaQuery.of(context).size.height * 0.6,
                  child: ListView(
                    children: <Widget>[
                      Text(
                        'Arrays',
                        style: TextStyle(fontSize: 16),
                      ),
                      Text(
                        'LinkedList',
                        style: TextStyle(fontSize: 16),
                      ),
                      Text(
                        'Stack',
                        style: TextStyle(fontSize: 16),
                      ),
                      Text(
                        'Tree',
                        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.


Similar Reads

Flutter - Custom Widgets
We create Custom Widgets when we want a custom look and feel to our app, and we know that there will be a repetition of a particular widget. We can create the custom widget in a new dart file with all the codes and defining the parameters that we need in the constructor. For more on how to split widgets, you can visit the article on Flutter - Split
8 min read
Flutter - Row and Column Widgets
Row and Column are the two most important and powerful widgets in Flutter. These widgets let you align children horizontally and vertically as per the requirement. As we know that when we design any UI(User Interface) in a flutter, we need to arrange its content in the Row and Column manner so these Row and Column widgets are required when designin
6 min read
How to Add Space Between Widgets in Flutter?
In this article, we'll learn how to add space between widgets. There are many options available in flutter which you can use to provide space and make UI attractive. If you use Row and Column for arranging widgets, then by default limited options are available for alignment. There are many options available for the spacing of widgets like Padding,
4 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 methods of how to perform this. When to Split Widgets
5 min read
Flutter - Concept of Visible and Invisible Widgets
In this article, we will see how we can change the visibility of widgets in flutter. We will learn about various methods for managing the visibility of flutter widgets. There are a couple of ways to manage the visibility of widgets in flutter. Method 1: Using Visibility class It has a visible property that manages whether the child is included in t
6 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 the entire widget subtree is stateless. Now let us
5 min read
How to Get Coordinates Widgets using rect_getter Package in Flutter?
Sometimes we need to get a widget's location or show some overlay widget or something similar over a widget whose location on the screen could be dynamic. In this article, we are going to discuss the way to get coordinates of a widget using the rect_getter package. Follow the steps below : 1. Create an App: Create a new flutter app by running the b
9 min read
Life Cycle of Flutter Widgets
Stateless Widgets: The widgets which remain constant throughout the lifetime of the app are called stateless widgets. We use them when we want structures to stay the same all over the app, for example, the AppBar, color scheme, i.e. generally the User Interface(UI). These widgets are immutable, i.e. they cannot be changed. Here Hot Reload can refle
2 min read
What are Widgets Available in Flutter?
Flutter is a mobile app development framework that allows developers to create beautiful and responsive user interfaces with ease. This is made possible through the use of Flutter widgets, which are the building blocks of every Flutter application. In Flutter, widgets are the fundamental building blocks of the user interface. They are a collection
4 min read
Animated Widgets in Flutter
The animations are considered hard work and take time to learn. Flutter made it easy with its packages. To animate the widgets without much effort, we can wrap them inside different defined animated widgets in the animate_do package. In this article, we will see how with the animate_do package we can animate widgets easily and enhance the user expe
4 min read