如何有条件地将小部件添加到列表? [英] How to conditionally add widgets to a list?
问题描述
在混乱中,诸如 Row
/ ListView
/ Stack $ c之类的小部件$ c>不处理空孩子。因此,如果我们要有条件地将小部件添加为子级,我通常会执行以下操作:
Row(
children:< Widget> [
foo == 42?Text( foo):Container(),
],
);
但是添加一个空容器感觉很奇怪。
另一个解决方案是其中
过滤器:
Row(
子级:< Widget> [
foo == 42?Text( foo):null,
] .where((t)=> t!= null).toList (),
);
这解决了空容器的问题,但是我们仍然有一个丑陋的三元组,写起来很累。 / p>
有没有更好的解决方案?
编辑:
自Dart 2.2起,新语法就本机支持:
列(
个孩子:[
if(foo!= null)Text(foo),
Bar(),
],
);
此问题目前在github 此处。
但是现在,您可以使用dart sync *
函数:
Row(
个孩子:toList(()sync * {
if(foo == 42){
yield Text( foo);
}
}),
);
其中 toList
是:
typedef Iterable< T> IterableCallback< T>();
List< T> toList< T>(IterableCallback< T> cb){
return List.unmodifiable(cb());
}
不仅可以解决有条件加法问题;由于 yield *
,它还允许传播算子。示例:
List< Widget> foo;
Row(
个孩子:toList(()sync * {
yield Text( Hello World);
yield * foo;
}) ,
);
In flutter, widgets such as Row
/ListView
/Stack
don't handle null children. So if we want to conditionally add widgets as children I usually do the following:
Row(
children: <Widget>[
foo == 42 ? Text("foo") : Container(),
],
);
But this feels weird to add an empty container.
Another solution is a where
filter :
Row(
children: <Widget>[
foo == 42 ? Text("foo") : null,
].where((t) => t != null).toList(),
);
This solves the empty container problem but we still have an ugly ternary and it is tiresome to write.
Is there any better solution?
EDIT:
Since Dart 2.2, new syntaxes supports this natively:
Column(
children: [
if (foo != null) Text(foo),
Bar(),
],
);
This problem is currently debated on github here.
But for now, you can use dart sync*
functions:
Row(
children: toList(() sync* {
if (foo == 42) {
yield Text("foo");
}
}),
);
where toList
is:
typedef Iterable<T> IterableCallback<T>();
List<T> toList<T>(IterableCallback<T> cb) {
return List.unmodifiable(cb());
}
Not only it solves the conditional addition problem; it also allows for a "spread operator" thanks to yield*
. Example:
List<Widget> foo;
Row(
children: toList(() sync* {
yield Text("Hello World");
yield* foo;
}),
);
这篇关于如何有条件地将小部件添加到列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!