Flutter with Redux:如何显示来自中间件的警报?我在哪里可以获得BuildContext

时间:2019-03-01 15:15:48

标签: android redux flutter

在具有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
     }
  });
}

有什么建议怎么做?

1 个答案:

答案 0 :(得分:1)

也许您可以将对话框作为回调传递:

  • 以这种方式创建您的请求操作:
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();
    }