How to add a ListView to a Column in Flutter?
I'm trying to construct a simple login page for my Flutter app. I've successfully built the TextFields and log in/Sign in buttons. I want to add a horizontal ListView. When I run the code my elements disappear, if I do it without the ListView, it's fine again. How can I do this correctly?
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: new Text("Login / Signup"),
),
body: new Container(
child: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new TextField(
decoration: new InputDecoration(
hintText: "E M A I L A D D R E S S"
),
),
new Padding(padding: new EdgeInsets.all(15.00)),
new TextField(obscureText: true,
decoration: new InputDecoration(
hintText: "P A S S W O R D"
),
),
new Padding(padding: new EdgeInsets.all(15.00)),
new TextField(decoration: new InputDecoration(
hintText: "U S E R N A M E"
),),
new RaisedButton(onPressed: null,
child: new Text("SIGNUP"),),
new Padding(padding: new EdgeInsets.all(15.00)),
new RaisedButton(onPressed: null,
child: new Text("LOGIN"),),
new Padding(padding: new EdgeInsets.all(15.00)),
new ListView(scrollDirection: Axis.horizontal,
children: <Widget>[
new RaisedButton(onPressed: null,
child: new Text("Facebook"),),
new Padding(padding: new EdgeInsets.all(5.00)),
new RaisedButton(onPressed: null,
child: new Text("Google"),)
],)
],
),
),
margin: new EdgeInsets.all(15.00),
),
),
);
Solution 1:
I've got this problem too. My solution is use Expanded
widget to expand remain space.
Column(
children: <Widget>[
Expanded(
child: horizontalList,
)
],
);
Solution 2:
Reason for error:
Column
expands to the maximum size in main axis direction (vertical axis), and so does the ListView
.
Solutions:
So, you need to constrain the height of the ListView
. There are many ways of doing it, you can choose that best suits your need.
-
If you want to allow
ListView
to take up all remaining space insideColumn
, useExpanded
.Column( children: <Widget>[ Expanded( // <-- Use Expanded child: ListView(...), ) ], )
-
If you want to limit your
ListView
to a certainheight
, useSizedBox
.Column( children: <Widget>[ SizedBox( height: 200, // Constrain height. child: ListView(...), ) ], )
-
If your
ListView
is small, you may tryshrinkWrap
property on it.Column( children: <Widget>[ ListView( shrinkWrap: true, // Set this ) ], )
-
If you want to make
ListView
to as small as it can be, useFlexible
withListView.shrinkWrap
:Column( children: <Widget>[ Flexible( // <-- Use Flexible child: ListView( shrinkWrap: true, // and set this ), ) ], )