Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use conditional statements/ternary inside a flutter widget

Tags:

flutter

dart

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')
      )
    ),
  );
};
like image 721
Sewer Avatar asked Jan 02 '23 13:01

Sewer


2 Answers

I think this is what your question is actually about ?

enter image description here

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
      ),
    );
  }
}
like image 157
Shady Aziza Avatar answered Jan 10 '23 21:01

Shady Aziza


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')
      )
    ),
  );
};
like image 39
BambinoUA Avatar answered Jan 10 '23 21:01

BambinoUA