Flutter - Auto size AlertDialog to fit list content
Wrap your Container
inside a Column
, in the content paramenter, inside of it, set the mainAxisSize.min
, in Column property
I know it's quite late, but have you tried this?
Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(
child: ListView.builder(
shrinkWrap: true,
...
),
)
],
);
Don't set mainAxisSize.min
in your Column
otherwise you might run into overflow error if the content is longer than the viewport. To solve this issue, use either of the approaches.
1. Set scrollable: true
in AlertDialog
:
AlertDialog(
scrollable: true, // <-- Set it to true
content: Column(
children: [...],
),
)
2. Wrap Column
in SingleChildScrollView
:
AlertDialog(
content: SingleChildScrollView(
child: Column(
children: [...],
),
),
)
3. Set shrinkWrap: true
in ListView
:
AlertDialog(
content: SizedBox(
width: double.maxFinite,
child: ListView(
shrinkWrap: true, // <-- Set this to true
children: [...],
),
),
)
I have a similar problem.
I fixed it by adding: scrollable: true
in AlertDialog
Updated Code will be :
createDialog() {
fetchCities().then((response) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
scrollable: true,
title: Text('Wybierz miasto'),
content: Container(
height: 200.0,
width: 400.0,
child: ListView.builder(
shrinkWrap: true,
itemCount: response.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(response[index].name),
onTap: () => citySelected(response[index].id),
);
},
),
),
);
}
);
});
}