flutterdartsetstateshowdialog

setstate doesn't work with showdialog and alertdialog


Using a stateful widget and setstate with showdialog and alertdialog seems to not work properly in my code but for simplification i simulated the same issue with smaller and simpler code here for more problem understanding

import 'package:flutter/material.dart';
import '../widgets/app_drawer.dart';

class Test extends StatefulWidget {

  @override
  State<Test> createState() => _TestState();
}

class _TestState extends State<Test> {

  int x = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: AppDrawer(),
      appBar: AppBar(
        title: Text("Shop"),
      ),
      body: Column(
        children: [
          RaisedButton(
            onPressed: () {
              showDialog(
                context: context,
                builder: (ctx) => AlertDialog(
                  title: Text("hey"),
                  content: Text(x.toString()),
                  actions: [
                    RaisedButton(
                      onPressed: () {},
                      child: Text("click me"),
                    ),
                    RaisedButton(
                      onPressed: () {
                        setState(() {
                          x++;
                        });
                      },
                      child: Text("increment"),
                    )
                  ],
                ),
              );
            },
            child: Text("Click"),
          ),
          Text(x.toString()),
        ],
      ),
    );
  }
}

if you run this piece of code you will notice the number increasing in the background but not on the popup dialog and to see the change you have to close the dialog and reopen it to see the latest value the actual code (the not simplified version) is based on the same idea but a little different

the idea is based on a shop order where you see your cart with products and when you click on edit cart products a popup dialog appears with the previous values for the products and can remove or add products from the cart and click on Update button. the onPressed value for the button can be a function which approves the new cart if the products list is not null and can be null (disabled button) if you removed all products from the cart but it doesn't seem to work immediately. the button looks something like this

RaisedButton(
  onPressed: orderCart.isEmpty
  ? null
  : () {
       //Function here
    },
  child: Text(
       "Update",
      ),
  ),

Solution

  • You should use StatefulBuilder in showDialog to use setState((){});

    ...
    body: Column(
      children: [
        RaisedButton(
          onPressed: () {
            showDialog(
              context: context,
              builder: (BuildContext context) {
                return StatefulBuilder(
                  builder: (context, StateSetter setState) {
                    return AlertDialog( 
    ...