I need to know is it possible to use ternary/if else inside flutter widgets.
I'm trying to create a buttonCreator widget which will take few parameters, one of which will be the background. I need to check whether the widget has background enabled or not. What i have is this but i have no idea how to use it in real dart code.
Container buildButton(String text, bool bg){
return new Container(
decoration: new BoxDecoration(
border: new Border.all(color: Colors.white),
if (bg != true ? color: Colors.white : '')
),
padding: new EdgeInsets.all(15.0),
margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
child: new Center(
child: new Text(
text, style: new TextStyle(color: Colors.white, fontFamily: 'Monsterrat')
)
),
);
};
I think this is what your question is actually about ?
import 'package:flutter/material.dart';
void main() => runApp(new MaterialApp(
home: new Home(),
));
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Flexible(
child: new MyContainer(
color: Colors.red,
),
),
new Flexible(
child: new MyContainer(
img: "http://www.clker.com/cliparts/F/v/O/6/E/c/cartoon-rubber-duck-hi.png",
),
)
],
),
),
);
}
}
class MyContainer extends StatelessWidget {
String img;
Color color;
MyContainer ({this.img,this.color});
@override
Widget build(BuildContext context) {
return this.img!=null? new Container(
decoration: new BoxDecoration(
image:new DecorationImage(
image: new NetworkImage(this.img)
)
),
): new Container(
decoration: new BoxDecoration(
color: this.color
),
);
}
}
Container buildButton(String text, bool bg){
return new Container(
decoration: new BoxDecoration(
border: new Border.all(color: Colors.white),
color: bg ? Colors.white : null, // you can use ternary operator here
),
padding: new EdgeInsets.all(15.0),
margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
child: new Center(
child: new Text(
text, style: new TextStyle(color: Colors.white, fontFamily: 'Monsterrat')
)
),
);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With