Dart 如何在颤振小部件中使用条件语句/三元
我需要知道是否可以在颤振窗口小部件中使用Trigonal/if-else 我正在尝试创建一个buttonCreator小部件,它将接受几个参数,其中一个参数是背景。我需要检查小部件是否启用了后台。我有的是这个,但我不知道如何在真正的dart代码中使用它Dart 如何在颤振小部件中使用条件语句/三元,dart,flutter,Dart,Flutter,我需要知道是否可以在颤振窗口小部件中使用Trigonal/if-else 我正在尝试创建一个buttonCreator小部件,它将接受几个参数,其中一个参数是背景。我需要检查小部件是否启用了后台。我有的是这个,但我不知道如何在真正的dart代码中使用它 Container buildButton(String text, bool bg){ return new Container( decoration: new BoxDecoration( border: new B
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')
)
),
);
};
我想这就是你的问题的实质
导入“包装:颤振/材料.省道”;
void main()=>runApp(新材料应用(
家:新家(),
));
类Home扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
归还新脚手架(
正文:新中心(
子:新列(
mainAxisAlignment:mainAxisAlignment.center,
儿童:[
新柔性(
儿童:新型MyContainer(
颜色:颜色,红色,
),
),
新柔性(
儿童:新型MyContainer(
img:“http://www.clker.com/cliparts/F/v/O/6/E/c/cartoon-rubber-duck-hi.png",
),
)
],
),
),
);
}
}
类MyContainer扩展了无状态小部件{
字符串img;
颜色;
MyContainer({this.img,this.color});
@凌驾
小部件构建(构建上下文){
返回此.img!=null?新容器(
装饰:新盒子装饰(
图片:新装饰图片(
image:newnetworkimage(this.img)
)
),
):新货柜(
装饰:新盒子装饰(
颜色:这个
),
);
}
}
根据AleksTi的回答修改
color
属性不能为null
此属性的可能重复项不是重复项,我需要返回一个具有值的对象,而不仅仅是值本身。
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')
)
),
);
};
decoration: new BoxDecoration(
border: new Border.all(color: Colors.white),
color: bg ? Colors.transparent : Colors.red, // you can use ternary operator here
),