如何在flift小部件中使用条件语句/三进制 [英] How to use conditional statements/ternary inside a flutter widget

查看:57
本文介绍了如何在flift小部件中使用条件语句/三进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道在flutter小部件中是否可以使用三元/如果没有的话.

I need to know is it possible to use ternary/if else inside flutter widgets.

我正在尝试创建一个buttonCreator小部件,该小部件将使用很少的参数,其中一个将是背景.我需要检查小部件是否启用了后台.我所拥有的是这个,但是我不知道如何在真实的Dart代码中使用它.

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
      ),
    );
  }
}

这篇关于如何在flift小部件中使用条件语句/三进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆