Home > Back-end >  How to make a save changes button?
How to make a save changes button?

Time:08-04

I have an AlertDialog that I use as a settings window, when the user opens it, the Apply button is not active, I would like that when the settings change, the button becomes active and saves the changes. How can I do this?

showAlertDialogSettings(BuildContext context, state) {

 Widget okButton = TextButton(
    child: Text("Apply"), 
    onPressed:  null, 
  );
  
  Widget cancelButton = TextButton(
    child: Text("Close"),
    onPressed:() => Navigator.pop(context),
  );

  AlertDialog alert = AlertDialog(

    title: Center(child: Text("Settings")),
    content:  Column(
          mainAxisSize: MainAxisSize.min,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
          Text('Sound:'),
          SwitchWidget(),
        ],),
        SizedBox(
          height: 48,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
            Text('Difficulty:'),
            Padding(
              padding: const EdgeInsets.only(right: 5),
              child: DropDownButtonSettingsWidget()
            ),
          ],),
        ),  
      ],
    ),
  
    actions: [
      okButton,
      cancelButton,

    ],
  );

  showDialog(
    context: context,
    builder: (BuildContext context) {
      return BackdropFilter (  
      filter: ImageFilter.blur(sigmaX: 6, sigmaY: 6), 
      child: alert );
    },
  );
}

enter image description here

CodePudding user response:

You will need to maintain state of both the sound and the difficulty values (there are many ways to tackle this), though the simplest would be to split out the "body" of the AlertDialog to be a StatefulWidget to contain its state. From there, you can check whether values have changed and update the view state to enable the apply button.

It's highly recommended to not mix business logic with UI logic, so this widget shouldn't actually do any of the saving. Inputs can be encapsulated within a class, and then this class can be passed back via Navigator.of(context).pop(T) (where T is your value class, see docs) upon closing the dialog from the apply button callback.

// Input passed back via `pop(T)` can be retrieved via:
final input = await showDialog(MyAlertDialog());
  • Related