Posted in Dart Flutter

Flutter – How to use Conditional Statement (If Else) on Child Attribute

Flutter – How to use Conditional Statement (If Else) on Child Attribute Posted on May 13, 2020Leave a comment
I'm Hari Prasad Chaudhary from Nepal, developer of the finest educational website/app "MeroSpark" and the finest eCommerce system "PasalaY". Here I share the code snippet which I learn during development.

During building an app, sometimes we need to show content according to condition using if..else statement. But in Flutter, we can’t place if…else statement directly on child attribute because it accepts only widgets. But you can apply conditions child attribute like shown on the example below.

bool isloading = false; //example boolean for condition

Center(
   child: isloading? //set conditional with boolean isloading
   Text("Is Loaded"): //on true
   CircularProgressIndicator(), //on false 
)

// ":" and "?" is important
// this is code snippt, place 
// bool isloading = false; declaration above widget build

Show text according to condition with Text() Widget

bool loaded = true;
Text(
    loaded? //check the boolean loaded
    'Is Loaded': //on true
    'Is Not Loaded' //on false
)

// ":" and "?" is important
//this is code snippt, place 
//int x = 11 declaration above widget build

Using comparison statement:

int x = 11;
Text(
   x > 10? //check if x is greater than 10
   'X is greater than 10' : //on true
   'X is not greater than 10' //on false
)

// ":" and "?" is important
// this is code snippt, place 
// int x = 11 declaration above widget build

Using another function:

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

class ConditionalStatement extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    return _ConditionalStatement();
  }
}

class _ConditionalStatement extends State<ConditionalStatement>{
  int x = 11;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
         body: Center( 
              child:condition(x > 10),
         )
    );
  }

  Widget condition(bool val){
     if(val){
         //if val is true
         return Text("X is greater than 10");
     }else{
         //if val is false
         return Text("X is not greater than 10");
     }
  }

}

In this way you can set condition on child attribute.

I'm Hari Prasad Chaudhary from Nepal, developer of the finest educational website/app "MeroSpark" and the finest eCommerce system "PasalaY". Here I share the code snippet which I learn during development.

Leave a Reply

Your email address will not be published. Required fields are marked *