【问题标题】:Flutter dialog with MVC使用 MVC 的颤振对话框
【发布时间】:2021-11-17 17:05:15
【问题描述】:

我正在尝试显示一个带有 MVC 模式的对话框。

我希望对话框成为一个小部件。像这样:

AlertDialog gameDecisionDialog({
  required VoidCallback onClick,
  required String strDecision,
  required Color decisionColor,
  required BuildContext context,
}) {
  return AlertDialog(
    titleTextStyle: const TextStyle(
      fontWeight: FontWeight.bold,
      color: Colors.black,
      fontSize: 20,
    ),
    actionsOverflowButtonSpacing: 20,
    actions: [
      ElevatedButton(
        onPressed: () {
          Navigator.of(context).pop();
          return onClick();
        },
        child: const Icon(Icons.next_plan_outlined),
      ),
    ],
    content: Text(strDecision),
  );
}

此对话框将在模型层中调用。根据应用程序期间发生的情况,将出现一个对话框。问题在于 context 部分。

将上下文从视图层传递到控制器层然后再传递到模型层是否有意义?似乎效率低下。

关于如何做到这一点的任何想法?我试图避免在视图层中有对话框,它会变得太乱。

----------------更新

将我的代码修改为以下建议,但现在我的警报对话框没有出现。

看下面的代码(当点击按钮做一些事情然后显示对话框):

elevatedRectButton(
                    onClick: () {
                      setState(() {
                        MyController.stop();
                        gameDecisionDialog(
                          onClick: () {
                            MyController.start();
                          },
                          gameDecision: MyController.getGameDecision,
                          decisionColor: Colors.amber,
                          context: context,
                        );
                      });
                    },
                    mIcon: const Icon(Icons.do_not_touch),
                    subText: 'STOP',
                    minWidth: 20,
                    height: 20,
                    bgColor: Colors.red,
                  ),

我担心在小部件中调用小部件可能会导致此问题?

【问题讨论】:

    标签: flutter model-view-controller dialog


    【解决方案1】:

    不建议将 BuildContext 传递给模型/控制器。尝试在模型中的工作完成后或抛出错误时从小部件调用警报。

    Example: 
    
    onPress: () async {
    
      //Some trigger callback 
    
      startLoading(); 
    
      await controller.doWork().catchError((e) {
        stopLoading();
        showAlert(context, 'Some Message etc');
      });
    
      stopLoading();
     
    }
    

    【讨论】:

    • 谢谢你!在模型中的工作完成后,您从小部件中调用警报是正确的!有时你看东西太久而忘记它是那么容易!
    • 看来我的下一个问题是对话框没有弹出...
    • 看起来您可能需要在警报函数中调用 showDialog 或 showCupertinoDialog 函数。返回一个对话框不会显示它。您可以更改警报方法以不返回任何内容,但只要在其中调用 showDialog,它就会显示警报。
    • 是的.....现在才知道...谢谢!
    猜你喜欢
    • 2022-11-11
    • 2020-06-02
    • 2018-11-13
    • 1970-01-01
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    相关资源
    最近更新 更多