在 Flutter bloc 侦听器中延迟状态检查
Delay state check inside Flutter bloc listener
我正在通过一个 bloc 向服务器发送数据,并在发送过程中显示 progressSnackBar
,然后在成功时显示 successSnackBar
。有时这需要不到一秒钟的时间,根本不显示 progressSnackBar
是有意义的 - 换句话说 等一下,然后检查状态是否仍然是 UpdatingAccount
。我已经尝试并失败了涉及 Future.delay(...)
的不同组合,我可能会做一个 setState
hack 但是有没有办法在 bloc listener 中实现这个?
BlocListener<AccountBloc, AccountState>(
listener: (BuildContext context, state) {
if (state is UpdatingAccount) { // <-- delay this
Scaffold.of(context)
..hideCurrentSnackBar()
..showSnackBar(progressSnackBar());
} else if (state is AccountUpdated) {
Scaffold.of(context)
..hideCurrentSnackBar()
..showSnackBar(successSnackBar());
}
},
// rest...
),
您可以在 state is UpdatingAccount
条件下执行 Future.delay()
并再次检查状态。
if (state is UpdatingAccount) {
Future.delayed(Duration(seconds: 1), (){
if(state is "UpdatingAccount"){
Scaffold.of(context)
..hideCurrentSnackBar()
..showSnackBar(progressSnackBar());
}
});
}
我最终让小部件有状态并给它一个 _updated
bool 成员。
BlocListener<AccountBloc, AccountState>(
listener: (BuildContext context, state) {
if (state is UpdatingAccount) {
_updated = false;
Future.delayed(Duration(seconds: 1), () {
if (!_updated) {
Scaffold.of(context)
..hideCurrentSnackBar()
..showSnackBar(progressSnackBar());
}
});
} else if (state is AccountUpdated) {
_updated = true;
Scaffold.of(context)
..hideCurrentSnackBar()
..showSnackBar(successSnackBar());
}
},
// rest...
),
我正在通过一个 bloc 向服务器发送数据,并在发送过程中显示 progressSnackBar
,然后在成功时显示 successSnackBar
。有时这需要不到一秒钟的时间,根本不显示 progressSnackBar
是有意义的 - 换句话说 等一下,然后检查状态是否仍然是 UpdatingAccount
。我已经尝试并失败了涉及 Future.delay(...)
的不同组合,我可能会做一个 setState
hack 但是有没有办法在 bloc listener 中实现这个?
BlocListener<AccountBloc, AccountState>(
listener: (BuildContext context, state) {
if (state is UpdatingAccount) { // <-- delay this
Scaffold.of(context)
..hideCurrentSnackBar()
..showSnackBar(progressSnackBar());
} else if (state is AccountUpdated) {
Scaffold.of(context)
..hideCurrentSnackBar()
..showSnackBar(successSnackBar());
}
},
// rest...
),
您可以在 state is UpdatingAccount
条件下执行 Future.delay()
并再次检查状态。
if (state is UpdatingAccount) {
Future.delayed(Duration(seconds: 1), (){
if(state is "UpdatingAccount"){
Scaffold.of(context)
..hideCurrentSnackBar()
..showSnackBar(progressSnackBar());
}
});
}
我最终让小部件有状态并给它一个 _updated
bool 成员。
BlocListener<AccountBloc, AccountState>(
listener: (BuildContext context, state) {
if (state is UpdatingAccount) {
_updated = false;
Future.delayed(Duration(seconds: 1), () {
if (!_updated) {
Scaffold.of(context)
..hideCurrentSnackBar()
..showSnackBar(progressSnackBar());
}
});
} else if (state is AccountUpdated) {
_updated = true;
Scaffold.of(context)
..hideCurrentSnackBar()
..showSnackBar(successSnackBar());
}
},
// rest...
),