Listview doesn’t display in AlertDialog | A Flutter guide
This might not sound like a highlighted topic instead but it can’t be ignored too. This quick guide will help us sort out this Flutter problem. So let’s begin.
Table of Contents
Project Structure
Ways to handle this problem
Project Structure
We will be having a Floating Action Button (FAB) with an onPressed event directing towards a function that shows AlertDialog. The following snippet jots down the complete stuff.
return Scaffold(
body: Center(
child: Text("Problem Solving #5"),
),
floatingActionButton: FloatingActionButton(
child: Text("Dialog"),
onPressed: () => dialoger(context),
),
);
}
dynamic dialoger(BuildContext context) {
showDialog(context: context, builder: (_) {
return AlertDialog(
title: Text("Listview"),
content: ListView.builder(
itemCount: 30,
itemBuilder: (_, i) {
return Text("Item $i");
},
),
);
});
}
In the next section, let’s look at the ways we can come out of this problem.
Ways to handle this problem
Upon running the application we are surrounded by this error.
Here, you might say (If you remember the code snippet I placed above) that,
Adding “shrinkWrap: true” will definitely solve the issue as we have seen it several times. This command always comes to the rescue.
But
This will result in the same error.
So what’s the solution
Here I will discuss two ways to handle this.
We will make use of a property “double.maxFinite” and apply this as the width of our Widget. We can use Container or SizedBox or any that has width available.
Upon modifications, our snippet will look like this,
dynamic dialoger(BuildContext context) {
showDialog(context: context, builder: (_) {
return AlertDialog(
title: Text("Listview"),
content: SizedBox(
width: double.maxFinite,
child: ListView.builder(
itemCount: 50,
itemBuilder: (_, i) {
return Text("Item $i");
},
),
),
);
});
}
I have wrapped ListView with SizedBox and applied width. Secondly, I have increased the item count to 50.
It’s time to check the app again.
What if Listview itself is treated as a child i.e. Used Column or Wrap.
In that case, we will make use of this same command. Consider this snippet
dynamic dialoger(BuildContext context) {
showDialog(context: context, builder: (_) {
return AlertDialog(
title: Text("Listview"),
content: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
width: double.maxFinite,
child: ListView.builder(
itemCount: 50,
itemBuilder: (_, i) {
return Text("Item $i");
},
),
],
),
);
});
}
This would result in the same output.
Winding up
So, We have discussed two ways to get rid of this(not rarely highlighted) problem.
If you enjoyed reading then 👏.
Here’s a reference video for you!
If you have any queries about this article or others then feel free to ask. I will try my best to respond asap.
Follow me on GitHub
Remember me in your Prayers.