gpt4 book ai didi

dart - StreamBuilder 没有在流中的新事件上重建

转载 作者:行者123 更新时间:2023-12-03 03:26:08 27 4
gpt4 key购买 nike

我的 StreamBuilder 在 View 中:

Widget build(BuildContext context) {
print("rebuilding..."); // as of now this gets called only on view initialization and never again - i.e. not on new events going through alarmController.stream

return StreamBuilder(
stream: widget.bloc.alarmController.stream,
initialData: Alarm(''),
builder: (BuildContext context, AsyncSnapshot<Alarm> snapshot) {
if (!snapshot.hasData) {
return Center(
child: Text(StringLiterals.NO_ALARM_DATA_MSG))
);
}

return Switch(
activeColor: Colors.red,
value: snapshot.data.status == 'Started',
onChanged: (bool _value) {
_newAlarmValue = _value;
_askAlarmConfirmation();
}));
});
}

我 Bloc 的核心:

AlarmBloc(this.Api) {
getAlarm();
}
getAlarm() async {
Alarm response = await Api.getAlarmStatus();
alarmController.sink.add(response); // here im adding new event, therefore streambuilder should rebuild, right?
}

最后是我调用来启动新事件的代码(在本例中是 firebase 消息):

if(_message.notification.body.contains("Alarm") && IS_LOGGED_IN == true) {
alarmBloc.getAlarm();
}

所以问题是 StreamBuilder 不会在新事件通过 alarmController.stream 时重建。可能是什么原因?

最佳答案

您的 bloc 需要是一种 Stream。与您的 StreamBuilder 相同的流类型。例如,您的 Bloc 需要是 Stream<Alarm> .否则stream: widget.bloc.alarmController.stream,只会被调用一次,不会充当异步数据流。

您的 Streambuilder 需要检查连接状态

Widget build(BuildContext context) {
print("rebuilding..."); // as of now this gets called only on view initialization and never again - i.e. not on new events going through alarmController.stream

return StreamBuilder<Alarm>(
stream: widget.bloc.alarmController.stream,
initialData: Alarm(''),
builder: (BuildContext context, AsyncSnapshot<Alarm> snapshot) {
if (snapshot.hasError) return new Text('Error: ${snapshot.error}');
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Text('Loading...');
default:
if (!snapshot.hasData) {
return Center(
child: Text(StringLiterals.NO_ALARM_DATA_MSG))
);
}

return Switch(
activeColor: Colors.red,
value: snapshot.data.status == 'Started',
onChanged: (bool _value) {
_newAlarmValue = _value;
_askAlarmConfirmation();
}));
}

以下是您可以检查的其他类型的连接状态:

async.dart

    enum ConnectionState {
/// Not currently connected to any asynchronous computation.
///
/// For example, a [FutureBuilder] whose [FutureBuilder.future] is null.
none,

/// Connected to an asynchronous computation and awaiting interaction.
waiting,

/// Connected to an active asynchronous computation.
///
/// For example, a [Stream] that has returned at least one value, but is not
/// yet done.
active,

/// Connected to a terminated asynchronous computation.
done,
}

关于dart - StreamBuilder 没有在流中的新事件上重建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56278353/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com