Ad

Flutter Dialog With MVC

- 1 answer

I am trying to display a dialog box with MVC pattern.

I want the dialog box to be a widget. like so:

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),
  );
}

This dialog will be called in the model layer. Depending what happens during the app, a dialog will appear. The issue, is the context portion.

does it make sense to pass context from the view layer down to controller layer and then to model layer? Seems inefficient.

Any ideas on how to do this? I am trying to avoid having the dialog box in the view layer, its going to get too messy.

---------------- UPDATE

modified my code to the below suggestion, BUT now my alert dialog doesn't show up.

See the following code (when button clicked do some stuff and then display dialog):

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,
                  ),

I fear that calling a widget within a widget might be causing this issue?

Ad

Answer

Passing a BuildContext into a model/controller would not be recommended. Try to call the alert from the widget after the work in the model has been done or when an error is thrown.

Example: 

onPress: () async {

  //Some trigger callback 

  startLoading(); 

  await controller.doWork().catchError((e) {
    stopLoading();
    showAlert(context, 'Some Message etc');
  });

  stopLoading();
 
}
Ad
source: stackoverflow.com
Ad