Flutter 如何在颤振小部件(中心小部件)的子属性中使用条件语句
到目前为止,每当我需要在小部件中使用条件语句时,我都做了以下工作(使用中心和容器作为简化的虚拟示例): 尽管当我尝试使用if/else语句时,它会导致死代码警告:Flutter 如何在颤振小部件(中心小部件)的子属性中使用条件语句,flutter,if-statement,dart,conditional-statements,Flutter,If Statement,Dart,Conditional Statements,到目前为止,每当我需要在小部件中使用条件语句时,我都做了以下工作(使用中心和容器作为简化的虚拟示例): 尽管当我尝试使用if/else语句时,它会导致死代码警告: new Center( child: if(condition == true){ new Container(); }else{ new Container(); } ) 有趣的是,我尝试了switch-case语句,它给了我同样的警告,因此我无法运行代码。我是做错了什么,还是
new Center(
child:
if(condition == true){
new Container();
}else{
new Container();
}
)
有趣的是,我尝试了switch-case语句,它给了我同样的警告,因此我无法运行代码。我是做错了什么,还是因为我不能使用if/else或switch语句而不认为存在死代码?在Dart中,
if/else
和switch
不是表达式。它们不返回值,因此不能将它们传递给构造函数参数。如果您的构建方法中有很多条件逻辑,那么尝试并简化它是一个很好的实践。例如,您可以将自包含逻辑移动到方法,并使用if/else
语句初始化局部变量,以便以后使用
使用方法和if/else
使用if/else
我发现,使用条件逻辑构建颤振UI的一个简单方法是将逻辑保持在UI之外。以下是返回两种不同颜色的函数:
Color getColor(int selector) {
if (selector % 2 == 0) {
return Colors.blue;
} else {
return Colors.blueGrey;
}
}
下面的函数用于设置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),
],
);
},
);
newlistview.builder(
itemCount:users.length,
itemBuilder:(构建上下文,int索引){
返回新列(
儿童:[
新ListTile(
领先:新CircleAvatar(
背景颜色:getColor(索引),
子项:新文本(用户[索引]。名称[0])
),
标题:新文本(用户[索引]。登录),
字幕:新文本(用户[索引].name),
),
新隔板(高度:2.0),
],
);
},
);
非常简洁,因为您可以在多个小部件中重复使用颜色选择器功能。以下是解决方案。
我已经修好了。这是密码
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");
}
}
如果使用小部件列表,则可以使用:
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(),
)),
);
}
}
Column(
children: [
if (true) Text('true') else Text('false'),
],
)
类主页扩展了无状态小部件{
bool notNull(对象o)=>o!=null;
@凌驾
小部件构建(构建上下文){
var条件=真;
返回脚手架(
appBar:appBar(
标题:文本(“提供商演示”),
),
正文:中(
子:列(
儿童:[
条件?文本(“真”):空,
容器(
身高:300,
宽度:MediaQuery.of(context).size.width,
子项:文本(“测试”)
)
].where(notNull).toList(),
)),
);
}
}
另一种选择:对于类似于“开关的
”语句,有很多条件,我喜欢使用映射:
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),
};
在条件列表中添加/删除元素更容易,无需触摸条件语句
另一个例子:
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];
}
}
****也可以使用此方法使用条件****
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
)
),
)
),
实际上,您可以使用
if/else
和switch
以及在dart/flatter中内联的任何其他语句
使用即时匿名函数
把你的语句包装成一个函数
(() {
// your code here
}())
我强烈建议不要将太多的逻辑直接放在UI“标记”中,但我发现Dart中的类型推断需要一点工作,所以它有时在类似的场景中很有用
使用三元运算符
在集合中使用If或For语句或spread运算符
使用一种方法
重定义开关语句
作为三元运算符的另一种替代方法,您可以创建switch语句的函数版本,如下文所示
对于记录,Dart 2.3添加了在集合文本中使用if/else语句的功能。现在可以通过以下方式完成此操作:
return Column(children: <Widget>[
Text("hello"),
if (condition)
Text("should not render if false"),
Text("world")
],);
返回列(子项:[
文本(“你好”),
如果(条件)
文本(“如果为false,则不应呈现”),
文本(“世界”)
],);
您可以简单地使用条件语句
a==b?c:d
例如:
Container(
color: Colors.white,
child: ('condition')
? Widget1(...)
: Widget2(...)
)
我希望你明白了
假设如果没有其他条件,您可以使用SizedBox.shrink()
如果是列,则无需编写?:
运算符
Column(
children: <Widget>[
if('condition')
Widget1(...),
],
)
列(
儿童:[
如果('条件')
Widget1(…),
],
)
我个人使用if/else语句作为这种block语句的子语句。它仅支持Dart 2.3.0以上版本
如果/否则
Column(
children: [
if (_selectedIndex == 0) ...[
DayScreen(),
] else ...[
StatsScreen(),
],
],
),
如果/否则如果
Column(
children: [
if (_selectedIndex == 0) ...[
DayScreen(),
] else if(_selectedIndex == 1)...[
StatsScreen(),
],
],
),
这是一篇很棒的文章和对话。我试着使用三元运算符。但是代码没有工作,导致了前面提到的错误
Column(children: [ condition? Text("True"): null,],);
上面的三元示例是漏导。Dart将以返回null而不是小部件的错误进行响应。不能返回null。正确的方法是返回小部件:
Column(children: [ condition? Text("True"): Text("false"),],);
为了使三元程序正常工作,您需要返回一个小部件。如果你不想退回任何东西,你可以退回一个空容器
Column(children: [ condition? Text("True"): Container(),],);
祝你好运。在这种情况下,我建议使用三元运算符:
child:条件?容器():中心()
并尽量避免使用以下形式的代码:
if(条件)返回A,else返回B
这不需要比三元运算符更冗长
但如果需要更多的逻辑,您也可以:
使用Builder小部件
当需要子窗口小部件时,允许使用闭包:
柏拉图式小部件,调用闭包以获取其子小部件
无论何时您需要逻辑来构建小部件都很方便,它避免了创建专用功能的需要
将生成器小部件用作子部件,在其Builder
方法中提供逻辑:
中心(
孩子:建筑工人(
生成器:(上下文){
//任何需要的逻辑。。。
最终条件=_whateverLogicNeeded();
返回条件
?容器();
:中心();
}
)
)
建筑商提供了一个方便的地方来存放c
Container(
color: Colors.white,
child: ('condition')
? Widget1(...)
: Widget2(...)
)
Container(
color: Colors.white,
child: ('condition')
? Widget1(...)
: SizedBox.shrink()
)
Column(
children: <Widget>[
if('condition')
Widget1(...),
],
)
Column(
children: [
if (_selectedIndex == 0) ...[
DayScreen(),
] else ...[
StatsScreen(),
],
],
),
Column(
children: [
if (_selectedIndex == 0) ...[
DayScreen(),
] else if(_selectedIndex == 1)...[
StatsScreen(),
],
],
),
Column(children: [ condition? Text("True"): null,],);
Column(children: [ condition? Text("True"): Text("false"),],);
Column(children: [ condition? Text("True"): Container(),],);
bool _paused = false;
CupertinoButton(
child: _paused ? Text('Play') : Text('Pause'),
color: Colors.blue,
onPressed: () {
setState(() {
_paused = !_paused;
});
},
),
if(bool = true) Container(
child: ....
),
OR
if(bool = true) Container(
child: ....
) else new Container(child: lalala),
Column(
children: <Widget>[
if (isCondition == true)
Text('The condition is true'),
],
);
Column(
children: <Widget>[
Conditional.single(
context: context,
conditionBuilder: (BuildContext context) => someCondition == true,
widgetBuilder: (BuildContext context) => Text('The condition is true!'),
fallbackBuilder: (BuildContext context) => Text('The condition is false!'),
),
],
);
Column(
children: <Widget>[
ConditionalSwitch.single<String>(
context: context,
valueBuilder: (BuildContext context) => 'A',
caseBuilders: {
'A': (BuildContext context) => Text('The value is A!'),
'B': (BuildContext context) => Text('The value is B!'),
},
fallbackBuilder: (BuildContext context) => Text('None of the cases matched!'),
),
],
);
WidgetChooser(
condition: true,
trueChild: Text('This widget appears if the condition is true.'),
falseChild: Text('This widget appears if the condition is false.'),
);
import 'package:flutter/widgets.dart';
class WidgetChooser extends StatelessWidget {
final bool condition;
final Widget trueChild;
final Widget falseChild;
WidgetChooser({@required this.condition, @required this.trueChild, @required this.falseChild});
@override
Widget build(BuildContext context) {
if (condition) {
return trueChild;
} else {
return falseChild;
}
}
}
Column(
children: [
if (true) Text('true') else Text('false'),
],
)
(condition) ? statement1 : statement2
Center(child: condition ? Widget1() : Widget2())
child: Container(
child: isFile == true ?
Image.network(pathfile, width: 300, height: 200, fit: BoxFit.cover) :
Text(message.subject.toString(), style: TextStyle(color: Colors.white),
),
),
Container(
child: Builder(builder: (context) {
/// some operation here ...
if(someCondition) {
return Text('A');
}
else return Text('B');
})
)
class StatmentExample extends StatelessWidget {
Widget build(BuildContext context) {
return pageValue==1 ? Page1():pageValue== 2? Page2():pageValue==3 ? Page3():Page4();
}
}
Widget showIf(bool shouldShow, Widget widget) {
if (shouldShow) {
return widget;
} else {
return Container();
}}
Column(children: [showIf(myConditionIsTrue, myComplexWidget)])