在我使用 Redux 架构的 Flutter 聊天应用程序中,我需要在某些异步调用的结果后显示对话框。我的主要问题是获取当前的 BuildContext 以显示对话框。这个异步调用可以从不同的屏幕完成,我需要当前屏幕的上下文。
我在中间件方面的调用如下所示:
void _setCompanionToChat(String groupChatId) {
var documentReference = _getChatDocument(groupChatId);
documentReference.get().then((snapshot) {
var closed = snapshot[ChatDatabase.CLOSED_ATTRIBUTE];
if (snapshot.exists && !closed) {
// SOME OPERATIONS
} else {
// SHOW DIALOG
}
});
}
有什么建议吗?
最佳答案
也许您可以将对话框作为回调传递:
- 按以下方式创建请求操作:
class MyDataRequestAction {
...
Function onError;
MyDataRequestAction({this.onError});
}
- 在您的屏幕中,在 StoreConnector 中分派这些操作,例如
@override
Widget build(BuildContext context) {
...
StoreConnector<AppState, _MyScreenViewModel>(
onInit: (store) => store.dispatch(MyDataRequestAction(
onError: () => showDialog(context: context, builder: (context) => AlertDialog(...));
));
...
- 最后在您的中间件中:
class MyMiddleware extends MiddlewareClass<AppState> {
...
@override
void call(Store<AppState> store, action, NextDispatcher next) async {
...
_setCompanionToChat(groupChatId, action) // PASS THE ACTION!!
}
void _setCompanionToChat(String groupChatId, dynamic action) {
...
if (snapshot.exists && !closed) {
// SOME OPERATIONS
} else {
action.onError();
}
关于android - Flutter with Redux : How to show alert from middleware? 在哪里可以获得 BuildContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54947433/