Enable/disable CupertinoDialogAction depending on CupertinoTextField is empty or not

747 views Asked by At

I want to set CupertinoDialogAction to enable if CupertinoTextField is not empty else by default it should be disabled, also I have set the "isDefaultAction: false" but it is still clickable.

showDialog(
          context: context,
          builder: (BuildContext context) => CupertinoAlertDialog(
            actions: [
              CupertinoDialogAction(
                onPressed: () => (Navigator.of(context).pop()),
                child: Text("Cancel"),
              ),
              CupertinoDialogAction(
                child: Text("Save"),
                isDefaultAction: false,
              ),
            ],
            title: Text("New Folder"),
            content: Column(
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text("Enter a name for this folder"),
                ),
                Container(
                  height: 30,
                  child: CupertinoTextField(
                    controller: folderName,
                    placeholder: "Name",
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                )
              ],
            ),
          ),
        );
2

There are 2 answers

7
Akif On

If you want to disable a CupertinoDialogAction, you need to set the onPressed property to null. It will look like this:

       Bool isEnabled = false;

       @override
       void initState() {
         super.initState();

         folderName.addListener(enableButton); // addListened to your TextEditingController!
       }

It will set isEnabled to true.

      enableButton()
      {
        if(folderName.text != "")
        {
          setState(() {
            isEnabled = true;
          });
        }                
      }

And, then you can use this boolean field.

      CupertinoDialogAction(
              onPressed: !isEnabled 
                  ? null
                  : () {
                      // Do what you need!
                      // Save method!
                    },
              child: Text("Save"),
              isDefaultAction: false,
            ),
0
mg74 On
  1. Create a stateful widget that builds the list of actions and returns CupertinoAlertDialog with those actions. This widget should contain some state that indicates if the save action should be enabled or not. If it should not be enabled, put null into the onPressed handler.

  2. Write some handler that uses setState to set this enabled/disabled state depending on what the user is doing.

  3. Return your stateful widget from the showDialog builder