'Force ListView to shrink to contain children
The most similar question I could find was 'how to create a row of scrollable text boxes or widgets in flutter inside a ListView?', however their solution was just to assign a height to the ListView's Container:
import 'package:flutter/material.dart';
// Define a 'main' function to run when our app starts
void main() {
var app = new MaterialApp(
home: new SafeArea(
left: false,
top: true,
right: false,
bottom: false,
child: new Scaffold(
body: new Container(
color: Colors.green,
height: 50.0,
child: new ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
new Icon(Icons.check_circle, size: 50.0),
new Icon(Icons.add, size: 50.0),
new Icon(Icons.add, size: 50.0),
new Icon(Icons.add, size: 50.0),
new Icon(Icons.add, size: 50.0),
new Icon(Icons.add, size: 50.0),
new Icon(Icons.add, size: 50.0),
new Icon(Icons.add, size: 50.0),
new Icon(Icons.add, size: 50.0),
new Icon(Icons.add, size: 50.0),
new Icon(Icons.add, size: 50.0),
new Icon(Icons.add, size: 50.0),
new Icon(Icons.close, size: 50.0),
],
),
),
appBar: AppBar(
title: new Text("Hello")
),
),
),
);
runApp(app);
}
According to Julien Louage, a Container expands to fill its parent unless a child is added, in which case, it will shrink to accommodate the dimensions of the child. If you were to remove Container's height property, it will go back to filling its parent, as if it didn't contain a child.
The reasonable conclusion is that ListView is causing the issue; ListView wants to be as big as it can, and there is no apparent way to change this.
Other widgets like Row have methods of shrinking to contain children but ListView does not? To see an example of this as well as Container's sizing convention, remove some Icons to avoid pixel overflow and make the following changes:
//height: 50.0,
child: new Row(
crossAxisAlignment: CrossAxisAlignment.center,
//child: new ListView(
// scrollDirection: Axis.horizontal,
So how can I make ListView shrink to contain children (like Row can w/ CrossAxisAlignment.center) w/o setting the height of the Container? There should be a way!
Solution 1:[1]
Wrap listview into a container and set the size you want.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Olasoji Oluwadamilola |