Skip to content
Related Articles

Related Articles

Improve Article
Flutter – Outputting Widgets Conditionally
  • Last Updated : 26 Jan, 2021

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.



My Personal Notes arrow_drop_up
Recommended Articles
Page :