Flutter tutorials

How to use Conditional Statement (IF ELSE) on Child Widget in Flutter

Flutter conditionally show widget within child attribute using (if else) statement or ternary operator. This can be very overwhelming for beginners because you can’t directly use “if..else” statement in any of flutter widget either stateless or stateful. Because everything is about widget in flutter and you can not include Dart core codes anywhere in a widget except the ones have method return types. But when building an app, you have to surely show different content based on certain conditions. For example, when creating a registration app, you will like to show the registration form to unregistered users. And show profile or welcome page to already registered/login users of the app. So, guess what? All these needs to be done based on a condition.

But note that in Dart and flutter most conditional statement like if/else and switch are just statement and not expressions.  And because all flutter widget are just class constructors, you can not pass these conditions to them because they do not return a value. If you have to write a lot of logic to make a decision on what widget to show, then I suggest you use a self-contained logic in a separate method as shown in below examples.

There’re many ways to use conditions to show different child widget and below are the examples of the best ones.

Solution 1: Using conditional operators (?:) also called ternary operator:

Syntax:

condition ? Widget() : SomeWidget()

If the condition return true the Widget() is displayed else SomeWidget() is displayed. Widget and SomeWidget() could be any flutter widget even Custom.

bool isPageLoading = true;

Container( 
    child: isPageLoading? //check if isPageLoading is true or false
        CircularProgressIndicator(): //show progress indicator when page is loading (loading = true)
        Text("Page done loading"), //show this text when page is done loading (loading = false)
)

You can also use multiple conditions to show different widget with ternary operator:

bool isPageLoading = false;
bool error = true;

Container( 
//first check if isPageLoading is true or false then decide which widget to show
// note that this will be the first condition to be checked
    child: isPageLoading? 
//show progress on loading = true
 CircularProgressIndicator(): 
//when isPageLoading = false, and then check error is true or false
   error? Text("Error"):	
//if isPageLoading = false and error = false, then show this text
Text("Loaded and No Error"),)

Here’s another example of show child widget conditionally in flutter:

int userAge = 10;

Container( 
  // check if the user age is greater than or equal to 18 then decide which child widget to show
    child: userAge >= 18?
           Text("User age is greater than or equal to 18 ") :
           Text("User age is less than 18")
)

Here’s full example of using ternary operator to conditionally show widget in flutter

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
	return MaterialApp(
	title: 'DartAndFlutter',

	// set it to false to hide the debug banner
	debugShowCheckedModeBanner: false,
	theme: ThemeData(
		primarySwatch: Colors.black,
	),
	home: HomePage(),
	);
}
}

class HomePage extends StatelessWidget {

// Declare a Boolean variable and set it to true
final checked = true;
@override
Widget build(BuildContext context) {
	return SafeArea(
	child: Scaffold(
		// AppBar
		appBar: AppBar(
		title: Text(‘DartAndFlutter', style:TextStyle(fontWeight:FontWeight.bold)),
		),
		body: Column(
		children: <Widget>[
			// A Simple Text Widget that will be visible
			// all the time
			Text(
			'The First Widget',
			style: TextStyle(
				fontSize: 19,
				fontWeight: FontWeight.normal,
			),
			),
			/// if the condition is true
			/// [condition == true] then
			/// below Text will be displayed
			if (checked)
			Text(
				'Second Widget',
				style: TextStyle(
				fontSize: 19,
				fontWeight: FontWeight.bold,
				),
			)
		],
		),
	),
	);
}
}

All the above examples uses conditional statement (?:) or ternary operators for deciding which widget to show. The question mark symbol (?) act as an if-statement whiles the colon symbol (:) act as an else-statement. You got to be careful in using them in nested conditions. I suggest you take your time to understand how each work deeply before you start using it in nested conditions if not you will end up rendering unexpected widget.

Solution 2: Using IF….ELSE statement on children property in Row() and Column() widget:

int age = 18;

Column(
  children: [ 
    if(age > 18)...[
      Text("User is an adult"),
    ]else...[
        Center(
          Child: Text("User is below 18 years")
        )
    ]
])

You can also use condition to render children widget in a Row() widget:

int age = 18;

Row(
  children: [ 
    if(age > 18)...[
      Text("User is an adult"),
    ]else...[
        Center(
          Child: Text("User is below 18 years")
        )
    ]
])

Note that you can only apply this approach of showing child widget using conditional statement on only parent widget that has a “children” property like Column(), Row() and Wrap() widgets.

Solution 3: Using (IF….ELSE) statement on LayoutBuilder:

int userHeight = 15;

Container(
    child:LayoutBuilder(builder: (context, constraints) { 
        if(userHeight >= 20){
            return Text("userHeight is greater than or equal to 20");
        }else{
            return Text("userHeight is less than 20");
        }  
    })
)

The layoutBuilder in flutter is a method that takes in application context and a constraint. Because it’s a method that returns a widget, you can use if else statement directly in its code-block to construct a new widget.

Solution 4: Using a separate created Method or a Function:

class _MyAppState extends State<MyApp> {
  int age = 18;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
          body: showTheWidget()
      );
  }

  showTheWidget (){
     if(age >= 30){
        return Text("the user age is greater than or equal to 30");
     }else{
        return Text("The user age is less than 30");
     }
  }
}

All the above examples are ways of conditionally showing child widget in flutter parent widget.

Solution 5: Using a spread operator to render children widget

class MyWidget extends StatelessWidget {


@override

Widget build(BuildContext context) {

return Column(

children: <Widget>[

if (someConditionToCheck == true) ...[

Text('Widget one'),

Text('Widget two'),

Text('Widget three'),

],

],

);

}

}

Related Posts

Flutter vs React Native

5 Reasons Why You Should Choose Flutter Over React Native In 2023

Are you confused about choosing between Google Flutter and React Native for your next cross-platform-app? Well, in this article I will show you reasons why Flutter is much…

working with list in Dart/Flutter

How to Automatically Resize Flutter font size based on screen size

Automatically resize Flutter font size based on screen size accordingly to the width and height dimension of the device. There’re so many dimensions of mobile devices and because…

flutter-error-setstate-called-after-dispose

[Solved] Vertical viewport was given unbounded height Error in flutter

When you include Listview as child widget of Scroll view and a Column or when you try to create a UI that leads you to use gride-layout, you…

This Post Has One Comment

Comments are closed.