Flutter 如何有条件地将小部件添加到列表中?
在flatter中,诸如Flutter 如何有条件地将小部件添加到列表中?,flutter,dart,conditional-statements,flutter-widget,flutter-listview,Flutter,Dart,Conditional Statements,Flutter Widget,Flutter Listview,在flatter中,诸如行/列表视图/堆栈之类的小部件不处理空子项。因此,如果我们想有条件地将小部件添加为子部件,我通常会执行以下操作: Row( children: <Widget>[ foo == 42 ? Text("foo") : Container(), ], ); 这解决了空容器的问题,但我们仍然有一个丑陋的三元组,写起来很烦人 有更好的解决方案吗?编辑: 自Dart 2.2以来,新语法在本机上支持这一点: 列( 儿童:[ 如果(foo!=null)文本
行
/列表视图
/堆栈
之类的小部件不处理空子项。因此,如果我们想有条件地将小部件添加为子部件,我通常会执行以下操作:
Row(
children: <Widget>[
foo == 42 ? Text("foo") : Container(),
],
);
这解决了空容器的问题,但我们仍然有一个丑陋的三元组,写起来很烦人
有更好的解决方案吗?编辑:
自Dart 2.2以来,新语法在本机上支持这一点:
列(
儿童:[
如果(foo!=null)文本(foo),
Bar(),
],
);
这个问题目前正在github上讨论 但现在,您可以使用dart
sync*
函数:
Row(
children: 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());
}
以下是我使用的一个更简单的版本:
Row(
children: [
Text("always included"),
skipNulls([
icon,
label,
]),
],
);
skipNulls<T>(List<T> items) {
return items..removeWhere((item) => item == null);
}
行(
儿童:[
文本(“始终包含”),
skipNulls([
偶像
标签,
]),
],
);
skipNulls(列表项){
return items..removehere((item)=>item==null);
}
新的Dart语法允许在列表中使用“如果”,这导致了这个简单的解决方案:
Row(
children: <Widget>[
if (foo == 42) Text("foo"),
],
);
行(
儿童:[
如果(foo==42)文本(“foo”),
],
);
太棒了!(\u buildChildren())的列表如何,其中\u buildChildren
是一种sync*
方法?同样有效。但是当你想传递参数时,使用它会有点无聊。关闭使它更容易
Row(
children: [
Text("always included"),
skipNulls([
icon,
label,
]),
],
);
skipNulls<T>(List<T> items) {
return items..removeWhere((item) => item == null);
}
Row(
children: <Widget>[
if (foo == 42) Text("foo"),
],
);