W3Schools Learner's Blog

W3Schools Programming knowledge summary website

div

12/19/2021

AlertDialog with ListView in Flutter

How to show AlertDialog with ListView in Flutter?

AlertDialog has the ability to display different kinds of widgets. Here we will see the 3 different types of ListView to display the list in AlertDialog and how to set dialog width and height to fit actual items size.

ListView in Dialog

AlertDialog can display a list of items that are immediately actionable when selected. They don’t have any type of buttons.

Here we will display a simple list in the AlertDialog. We need to provide the ListView to the AlertDialog and that’s it, it will handle the rest.

  List<String> colorList = ['Orange', 'Yellow', 'Pink','White', 'Red', 'Black', 'Green'];

  Future<String> _askFavColor() async {
  
    return showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('Favorite Color'),
            content: Container(
              width: double.minPositive,
              child: ListView.builder(
                shrinkWrap: true,
                itemCount: colorList.length,
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(
                    title: Text(colorList[index]),
                    onTap: () {
                      Navigator.pop(context, colorList[index]);
                    },
                  );
                },
              ),
            ),
          );
        });
  }

Here we wrap ListView in Container and set the width to double.minPositive to auto-size AlertDialog. Alternatively, You can use dropdown menus to provide options in a non-modal, less disruptive way.



Checkbox List

We can select multiple items from the list using a checkbox. We can use this list when you want to select multiple items. Here we need to add a confirmation button(Cancel/Done) after the user selects items. Here we use the String Map to track selected items.

Map<String, bool> cityList = {
    'Balagam': false, 'Bangalore': false, 'Hyderabad': false, 'Chennai': false,
    'Delhi': false, 'Surat': false, 'Junagadh': false,
    'Porbander': false, 'Rajkot': false, 'Pune': false,
  };
  
  Future<Map<String, bool>> _preLocation() async {
    return showDialog(
        context: context,
        builder: (BuildContext context) {
          return StatefulBuilder(
            builder: (context, setState) {
              return AlertDialog(
                title: Text('Preferred Location'),
                actions: <Widget>[
                  FlatButton(
                    onPressed: () {
                      Navigator.pop(context, null);
                    },
                    child: Text('Cancle'),
                  ),
                  FlatButton(
                    onPressed: () {
                      Navigator.pop(context, cityList);
                    },
                    child: Text('Done'),
                  ),
                ],
                content: Container(
                  width: double.minPositive,
                  height: 300,
                  child: ListView.builder(
                    shrinkWrap: true,
                    itemCount: cityList.length,
                    itemBuilder: (BuildContext context, int index) {
                      String _key = cityList.keys.elementAt(index);
                      return CheckboxListTile(
                        value: cityList[_key],
                        title: Text(_key),
                        onChanged: (val) {
                          setState(() {
                            cityList[_key] = val;
                          });
                        },
                      );
                    },
                  ),
                ),
              );
            },
          );
        });
  }

Here we use StatefulBuilder to change its appearance in response to events triggered by user interactions or when it receives data.



Radio List in Dialog 

Confirmation dialogs give users the ability to provide final confirmation of a choice before committing to it, so they have a chance to change their minds if necessary.

If the user confirms a choice, it’s carried out. Otherwise, the user can dismiss the dialog. For example, users can listen to multiple ringtones but only make a final selection upon tapping “OK.”

List<String> ringTone = ['Luna','Oberon','Phobos','Rose','Sunset','Wood']

Future<String> _selectRingtone() async {
    return showDialog(
        context: context,
        builder: (BuildContext context) {
          return StatefulBuilder(
            builder: (context, setState2) {
              return AlertDialog(
                title: Text('Phone Ringtone'),
                actions: <Widget>[
                  FlatButton(
                    onPressed: () {
                      Navigator.pop(context, null);
                    },
                    child: Text('CANCEL'),
                  ),
                  FlatButton(
                    onPressed: () {
                      Navigator.pop(context, ringTone[_currentIndex]);
                    },
                    child: Text('OK'),
                  ),
                ],
                content: Container(
                  width: double.minPositive,
                  height: 300,
                  child: ListView.builder(
                    shrinkWrap: true,
                    itemCount: ringTone.length,
                    itemBuilder: (BuildContext context, int index) {
                      return RadioListTile(
                        value: index,
                        groupValue: _currentIndex,
                        title: Text(ringTone[index]),
                        onChanged: (val) {
                          setState2(() {
                            _currentIndex = val;
                          });
                        },
                      );
                    },
                  ),
                ),
              );
            },
          );
        });
  }


Confirmation dialogs provide both confirmation and cancel buttons. After a confirmation button is tapped, a selection is confirmed. If the cancel button is tapped, or the area outside the dialog, the action is canceled.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.