【发布时间】:2019-05-08 12:07:30
【问题描述】:
Flutter 中的 Stream builder 正在被召回。我不确定为什么。我相信问题可能是我在流构建器中有一个集团提供者。我的流 dataBloc.dataStream 没有改变,导致流构建器再次构建。不确定,我做错了什么。流构建器是否一次又一次地构建我的小部件而流没有任何变化。显然这不是真的!对吧?
Widget build(context) {
final DataBloc dataBloc = DataBlocProvider.of(context);
print("dropdown build called again");
// this doesn't print recursively so this is perfect.
// So my build is not getting called again.
return StreamBuilder(
stream: dataBloc.dataStream,
builder: (context, snapshot) {
//ToDo remove prints
print("dropdown ${snapshot.data}");
// there is no change in snapshot.data, however print is getting called recursively. This is bad and wrong
// so my stream builder is getting called again, and this is wrong
String key = dataElement.conditionalField;
String _valueArray = dataElement.conditionalValues.toString();
String conditionalValue =
_valueArray.substring(1, _valueArray.length - 1);
Map<String, String> dataMap = snapshot.hasData ? snapshot.data : {};
bool isVisible = true;
if (key != "" &&
dataMap.containsKey(key) &&
dataMap[key] == conditionalValue.toString()) {
isVisible = true;
} else if (key != "") {
isVisible = false;
}
return Visibility(
child: BlocDropDownProvider(
fieldName: dataElement.key,
dataBloc: dataBloc,
child: Card(
color: Colors.grey[100],
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
label,
new Container(
height: 8.0,
),
dropDown,
],
),
),
),
visible: isVisible? true:false,
);
控制台的输出是:
I/flutter (14422): dropdown {idnumber: 10}
I/flutter (14422): dropdown {idnumber: 10}
【问题讨论】:
-
它可能不是
StreamBuilder,但如果build()(包含StreamBuilder的那个)被调用,那么StreamBuilder添加的小部件也会重新构建。 -
我添加了我的第一个打印语句来检查。我的构建不再被调用。我已添加评论。问题是我的流生成器。那里有些不对劲!
-
这也可能是 Stream 一遍又一遍地发出相同的值。 (
{idnumber: 10}) -
您可以使用pub.dartlang.org/documentation/rxdart/latest/rx/Observable/…等内容过滤与前一个值相等的值
-
见
Stream#distinct()方法
标签: flutter flutter-layout flutter-dependencies flutter-sliver