Home > Blockchain >  Does the StatefulBuilder have something similar to initState?
Does the StatefulBuilder have something similar to initState?

Time:08-30

I am trying to make a loading dialog for when a credit card is being processed. The problem that I am running into is that I want to be able to update the dialogs state when my future has been completed.

It seems like the only way to update a dialogs state is by using a StatefulBuilder widget. I found this out because I tried to change cartLoading in my processPayment method and nothing happens.

I want it to automatically call processPayment() when the dialog is created instead of me having to hit a button. Is this possible?

class CartModel extends ChangeNotifier {
  bool _cartLoading = false;
  bool get cartLoading => _cartLoading;
  set setLoading(bool value) {
    _cartLoading = value;
    notifyListeners();
  }
Future<bool?> openLoadingDialog(BuildContext context) async {
    setLoading = true;
    return showDialog<bool?>(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setState) {
          return Dialog(
            child: Container(
              child: Column(
                children: [
                  CustomButton(
                      name: "Process payment",
                      onPressed: () {
                        setState(() => setLoading = true);
                        processPayment()
                         .then((value) => setState(() => setLoading = false));
                      },
                      primaryColor: Colors.black,
                      onPrimaryColor: Colors.white),
                  Center(
                    child: SizedBox(
                      width: 150,
                      height: 150,
                      child: cartLoading
                          ? const CircularProgressIndicator()
                          : const Text("Thank you for your order"),
                    ),
                  )
                ],
              ),
            ),
          );
        },
      ),
      barrierDismissible: false,
    );
  }
}

CodePudding user response:

It seems like the only way to update a dialogs state is by using a StatefulBuilder widget.

Not necessarily. You can just create a normal Widget:

class MyDialog extends StatefulWidget { ... }

class _MyDialogState extends State<MyDialog> {
  @override
  void initState() {
    super.initState();
    // Put your initialization logic here
  }

  @override
  Widget build(BuildContext context) {
    // Put your setState logic here
    return Dialog(
      child: Container(...),
    );
  }
}

Now pass it to showDialog:

showDialog<bool?>(
  context: context,
  builder: (context) => MyDialog(),
);
  • Related