Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 1092 Vote(s) - 3.48 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

#1
So far whenever I needed to use a conditional statement within a Widget I have done the following (Using Center and Containers as simplified dummy examples):

new Center(
child: condition == true ? new Container() : new Container()
)

Though when I tried using an if/else statement it would lead to an Dead code warning:

new Center(
child:
if(condition == true){
new Container();
}else{
new Container();
}
)

Interestingly enough I tried with a switch case statement and it gives me the same warning and thus I cannot run the code. Am I doing something wrong or is it so that one cannot use if/else or switch statements without flutter thinking there is dead code?
Reply

#2
In Dart, `if/else` and `switch` are statements not expressions. They don't return a value so you can't pass them to constructor params. If you have a lot of conditional logic in your build method, then it is a good practice to try and simplify it. For example, you can move self-contained logic to methods, and use `if/else` statements to initialize local variables which you can later use.
### Using a method and if/else

Widget _buildChild() {
if (condition) {
return ...
}
return ...
}

Widget build(BuildContext context) {
return new Container(child: _buildChild());
}

###Using an `if/else`

Widget build(BuildContext context) {
Widget child;
if (condition) {
child = ...
} else {
child = ...
}
return new Container(child: child);
}


Reply

#3
Here is the solution.
I have fixed it. Here is the code

child: _status(data[index]["status"]),

Widget _status(status) {
if (status == "3") {
return Text('Process');
} else if(status == "1") {
return Text('Order');
} else {
return Text("Waiting");
}
}
Reply

#4
I found out that an easy way to use conditional logic to build Flutter UI is to keep the logic outside of the UI. Here is a function to return two different colors:

Color getColor(int selector) {
if (selector % 2 == 0) {
return Colors.blue;
} else {
return Colors.blueGrey;
}
}


The function is used below to to set the background of the CircleAvatar.

new ListView.builder(
itemCount: users.length,
itemBuilder: (BuildContext context, int index) {
return new Column(
children: <Widget>[
new ListTile(
leading: new CircleAvatar(
backgroundColor: getColor(index),
child: new Text(users[index].name[0])
),
title: new Text(users[index].login),
subtitle: new Text(users[index].name),
),
new Divider(height: 2.0),
],
);
},
);

Very neat as you can reuse your color selector function in several widgets.
Reply

#5
if you use a list of widgets you can use this:

class HomePage extends StatelessWidget {
bool notNull(Object o) => o != null;
@override
Widget build(BuildContext context) {
var condition = true;
return Scaffold(
appBar: AppBar(
title: Text("Provider Demo"),
),
body: Center(
child: Column(
children: <Widget>[
condition? Text("True"): null,
Container(
height: 300,
width: MediaQuery.of(context).size.width,
child: Text("Test")
)
].where(notNull).toList(),
)),
);
}
}

Reply

#6
Another alternative: for '`switch's`' like statements, with a lot of conditions, I like to use maps:

return Card(
elevation: 0,
margin: EdgeInsets.all(1),
child: conditions(widget.coupon)[widget.coupon.status] ??
(throw ArgumentError('invalid status')));


conditions(Coupon coupon) => {
Status.added_new: CheckableCouponTile(coupon.code),
Status.redeemed: SimpleCouponTile(coupon.code),
Status.invalid: SimpleCouponTile(coupon.code),
Status.valid_not_redeemed: SimpleCouponTile(coupon.code),
};

It's easier to add/remove elements to the condition list without touch the conditional statement.

Another example:

var condts = {
0: Container(),
1: Center(),
2: Row(),
3: Column(),
4: Stack(),
};

class WidgetByCondition extends StatelessWidget {
final int index;
WidgetByCondition(this.index);
@override
Widget build(BuildContext context) {
return condts[index];
}
}




Reply

#7

****You can also use conditions by using this method** **

int _moneyCounter = 0;
void _rainMoney(){
setState(() {
_moneyCounter += 100;
});
}

new Expanded(
child: new Center(
child: new Text('\$$_moneyCounter',

style:new TextStyle(
color: _moneyCounter > 1000 ? Colors.blue : Colors.amberAccent,
fontSize: 47,
fontWeight: FontWeight.w800
)

),
)
),
Reply

#8
For the record, Dart 2.3 added the ability to use if/else statements in Collection literals. This is now done the following way:

return Column(children: <Widget>[
Text("hello"),
if (condition)
Text("should not render if false"),
Text("world")
],);
[Flutter Issue #28181 - Inline conditional rendering in list ][1]


[1]:

[To see links please register here]

Reply

#9
This is great article and conversation. I tried to use the ternary operator as described. But the code didn't work resulting in an error as mentioned.

Column(children: [ condition? Text("True"): null,],);

The ternary example above is miss leading. Dart will respond with an error that a null was returned instead of widget. You can't return null. The correct way will be to return a widget:

Column(children: [ condition? Text("True"): Text("false"),],);

In order for the ternary to work you need to return a Widget. If you don't want to return anything you can return a empty container.

Column(children: [ condition? Text("True"): Container(),],);

Good luck.
Reply

#10
You can simply use a conditional statement `a==b?c:d`

For example :

Container(
color: Colors.white,
child: ('condition')
? Widget1(...)
: Widget2(...)
)

I hope you got the idea.

Suppose if there is no else condition you can use a SizedBox.shrink()

Container(
color: Colors.white,
child: ('condition')
? Widget1(...)
: SizedBox.shrink()
)

If it is a column no need to write `?:` operator

Column(
children: <Widget>[
if('condition')
Widget1(...),
],
)
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through