My screen has three widgets :
- First one is a ListView of widgets, the number of widgets can be incremented with a button. I want the ListView to take only the required space that's why I wrapped it in Flexible, but I don't want it to exceed the height of 266. (If it takes more than 266px, it becomes scrollable).
- Second one is a widget that will take all the remaining space, it's wrapped in Expended.
- Third one is just a button with defined height.
The code is something like :
Scaffold(
body : Column(
children:[
Flexible(child: Widget1()),
Expanded(child: Widget2()),
Button(),
])
)
I tried wrapping the Flexible in a ConstrainedBox and gave it a max height of 266, but the Widget1 took all the 266 height.
In short, I want Widget1 to take the required space, but it can't exceed 266. Anyone has a solution for this?
CodePudding user response:
In listview add the property shrinkwrap: true, and wrap the Widget1 with container with BoxConstraints, maxheight: 266.
class UpdateListViewExample extends StatefulWidget {
const UpdateListViewExample({Key? key}) : super(key: key);
@override
State<UpdateListViewExample> createState() => _UpdateListViewExampleState();
}
class _UpdateListViewExampleState extends State<UpdateListViewExample> {
List list = [];
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Column(children: [
Flexible(
child: Container(
constraints: const BoxConstraints(
maxHeight: 266,
),
color: Colors.grey,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Widget1(list: list),
),
),
),
const Expanded(child: Widget2()),
ElevatedButton(
onPressed: () {
list.add(list.length 1);
setState(() {});
},
child: const Text("Click Me"),
),
])),
);
}
}
class Widget1 extends StatelessWidget {
const Widget1({Key? key, required this.list}) : super(key: key);
final List list;
@override
Widget build(BuildContext context) {
return ListView(
shrinkWrap: true,
children: [
for (var item in list)
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 40,
color: Colors.blue,
alignment: Alignment.center,
child: Text(
'$item',
style: const TextStyle(
color: Colors.white,
),
),
),
)
],
);
}
}
class Widget2 extends StatelessWidget {
const Widget2({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container();
}
}