dartshowdialog

showAlertDialog don t close when it is pressed "no"


hello i have this showAlertDialog and need close when "no" it is pressed. With this code, when i press "no" my page in background is closed and showAlertDialog stay open. I just want to close the showAlertDialog and leave the page as it was

showAlertDialog(BuildContext context) {
  Widget noButton = TextButton(
    child: const Text("no"),
    onPressed: () {
      Navigator.pop(context);
    },
  );
  Widget yesButton = TextButton(
    child: const Text("yes"),
    onPressed: () {},
  );

  AlertDialog alert = AlertDialog(
    title: const Text("Aviso"),
    content: const Text("Dejesa finalizar a sua compra?"),
    actions: [
      noButton,
      yesButton,
    ],
  );

  showDialog(
    context: context,
    builder: (BuildContext context) {
      return alert;
    },
  );
}

Solution

  • import 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: "Test",
          home: TestPage(),
        );
      }
    }
    
    class TestPage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text("Test")),
          body: Center(
            child: InkWell(
              onTap: () {
                showAlertDialog(context);
              },
              child: Text("PressMe"),
            ),
          ),
        );
      }
    
      showAlertDialog(BuildContext context) {
        Widget noButton = TextButton(
          child: const Text("no"),
          onPressed: () {
            Navigator.pop(context);
          },
        );
        Widget yesButton = TextButton(
          child: const Text("yes"),
          onPressed: () {},
        );
    
        AlertDialog alert = AlertDialog(
          title: const Text("Aviso"),
          content: const Text("Dejesa finalizar a sua compra?"),
          actions: [
            noButton,
            yesButton,
          ],
        );
    
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return alert;
          },
        );
      }
    }