Open In App

Flutter – Outputting Widgets Conditionally

Last Updated : 07 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.



Next Article

Similar Reads