How to create a horizontally scrolling table with fixed column in Flutter? - flutter

I would like to create a series of tables that you can scroll through vertically, each of which may have a different number of rows/columns from each other.
Within each table, I would like to have the leftmost column frozen in place, and the remaining columns in that table to be horizontally scrollable, in case there are a number of columns that do not fit in the width of the screen. See screenshot:
My initial plan was to use a ListView for the page-level vertical scrolling between tables, and within each table, there is a Row of Columns, where the first column is a static width, and the remaining columns are enclosed within a horizontally scrolling ListView. The error I'm getting from Flutter is not helping me determine what I need to do, but it clearly has to do with having to set bounds on child Widgets.
Error: (Fixed 7/9/19 by wrapping horizontal ListView with a fixed height container and shrinkwrapping the ListView)
The following assertion was thrown during performResize():
Horizontal viewport was given unbounded width.
Viewports expand in the scrolling direction to fill their container.In this case, a horizontal
viewport was given an unlimited amount of horizontal space in which to expand. This situation
typically happens when a scrollable widget is nested inside another scrollable widget.
If this widget is always nested in a scrollable widget there is no need to use a viewport because
there will always be enough horizontal space for the children. In this case, consider using a Row
instead. Otherwise, consider using the "shrinkWrap" property (or a ShrinkWrappingViewport) to size
the width of the viewport to the sum of the widths of its children.
New Error 7/9/19:
The following message was thrown during layout:
A RenderFlex overflowed by 74 pixels on the right.
The overflowing RenderFlex has an orientation of Axis.horizontal.
The edge of the RenderFlex that is overflowing has been marked in the rendering with a yellow and
black striped pattern. This is usually caused by the contents being too big for the RenderFlex.
Consider applying a flex factor (e.g. using an Expanded widget) to force the children of the
RenderFlex to fit within the available space instead of being sized to their natural size.
This is considered an error condition because it indicates that there is content that cannot be
seen. If the content is legitimately bigger than the available space, consider clipping it with a
ClipRect widget before putting it in the flex, or using a scrollable container rather than a Flex,
like a ListView.
The specific RenderFlex in question is:
RenderFlex#9bf67 relayoutBoundary=up5 OVERFLOWING
creator: Row ← RepaintBoundary-[<0>] ← IndexedSemantics ←
NotificationListener ← KeepAlive ← AutomaticKeepAlive ← SliverList ←
SliverPadding ← Viewport ← IgnorePointer-[GlobalKey#74513] ← Semantics ← Listener ← ⋯
parentData: (can use size)
constraints: BoxConstraints(w=404.0, 0.0<=h<=Infinity)
size: Size(404.0, 300.0)
direction: horizontal
mainAxisAlignment: start
mainAxisSize: max
crossAxisAlignment: center
textDirection: ltr
This was the issue I ran into originally before getting side-tracked with the first issue reported; I can't understand why my ListView is not creating a scrollable container.
Code:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My App',
home: Scaffold(
appBar: AppBar(
title: Text('My App'),
backgroundColor: Colors.teal[400],
),
body: MyClass(),
),
);
}
}
const double headerCellWidth = 108.0;
const double cellPadding = 8.0;
const double focusedColumnWidth = 185.0;
const double rowHeight = 36.0;
class MyClass extends StatefulWidget {
#override
_MyClassState createState() => _MyClassState();
}
class _MyClassState extends State<MyClass> {
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return ListView(
padding: EdgeInsets.all(5.0),
children: <Widget>[
Row(
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
color: Colors.grey,
padding: EdgeInsets.all(cellPadding),
width: headerCellWidth,
),
HeaderCell('ABC'),
HeaderCell('123'),
HeaderCell('XYZ'),
],
),
Container(
height: 300.0, // Could compute height with fixed rows and known number of rows in advance
child: ListView(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
children: <Widget>[
Column(
children: <Widget>[
Container(
color: Colors.grey[300],
padding: EdgeInsets.all(cellPadding),
height: rowHeight,
width: focusedColumnWidth,
),
NumberCell('89'),
NumberCell('92'),
NumberCell('91'),
NumberCell('90'),
NumberCell('91'),
NumberCell('89'),
],
),
Column(
children: <Widget>[
Container(
color: Colors.grey[300],
padding: EdgeInsets.all(cellPadding),
height: rowHeight,
width: focusedColumnWidth,
),
NumberCell('89'),
NumberCell('92'),
NumberCell('91'),
NumberCell('90'),
NumberCell('91'),
NumberCell('89'),
],
),
],
),
),
],
),
],
);
}
}
class HeaderCell extends StatelessWidget {
HeaderCell(this.text);
final String text;
#override
Widget build(BuildContext context) {
return Container(
height: rowHeight,
padding: EdgeInsets.all(cellPadding),
width: headerCellWidth,
child: Text(
text,
textAlign: TextAlign.left,
overflow: TextOverflow.ellipsis,
maxLines: 1,
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
);
}
}
class NumberCell extends StatelessWidget {
NumberCell(this.text);
final String text;
#override
Widget build(BuildContext context) {
return Container(
height: rowHeight,
width: focusedColumnWidth,
padding: EdgeInsets.all(cellPadding),
child: Text(
text,
),
);
}
}

Here is a quick example and this would be the result: Video
List<Widget> _buildCells(int count) {
return List.generate(
count,
(index) => Container(
alignment: Alignment.center,
width: 120.0,
height: 60.0,
color: Colors.white,
margin: EdgeInsets.all(4.0),
child: Text("${index + 1}", style: Theme.of(context).textTheme.title),
),
);
}
List<Widget> _buildRows(int count) {
return List.generate(
count,
(index) => Row(
children: _buildCells(10),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: SingleChildScrollView(
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: _buildCells(20),
),
Flexible(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: _buildRows(20),
),
),
)
],
),
),
);
}

So I tried to produce a minimum working bit of code, and ended up with a workable solution (even if all the details aren't ironed out, like the first locked column being of flexible width instead of a fixed width as desired). Hopefully this will help others trying to produce something similar. What's interesting is that the Table construct is needed here, because replacing the TableRow (wrapped by Table) with just a Row causes an overflow error. I would still be interested in understanding why that is since it seems crucial to the layout engine.
#override
Widget build(BuildContext context) {
return ListView(
padding: EdgeInsets.all(5.0),
children: <Widget>[
Table(
children: <TableRow>[
TableRow(
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
// first locked column items
],
),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
// table header items
],
),
Row(
children: <Widget>[
// data cells
],
),
Row(
children: <Widget>[
// data cells
],
),
],
),
),
],
),
],
),
],
);
}

If there is not much customization needed, for those needed a fixed header and first column table may also consider to use the horizontal_data_table package:
https://pub.dev/packages/horizontal_data_table
It basically is using the two list view approach.

Related

How to lay out Rows and Columns in Flutter widget

I am trying to build the UI for a simple screen with a few Text and TextBoxes but I am getting weird layout errors like this.
Error: Cannot hit test a render box that has never been laid out.
The hitTest() method was called on this RenderBox: RenderStack#487f4 NEEDS-LAYOUT NEEDS-PAINT:
creator: Stack ← _FloatingActionButtonTransition ← MediaQuery ← LayoutId-[<_ScaffoldSlot.floatingActionButton>] ← CustomMultiChildLayout ← AnimatedBuilder ← DefaultTextStyle ← AnimatedDefaultTextStyle ← _InkFeatures-[GlobalKey#0cc7b ink renderer] ← NotificationListener<LayoutChangedNotification> ← PhysicalModel ← AnimatedPhysicalModel ← ⋯
parentData: offset=Offset(0.0, 0.0); id=_ScaffoldSlot.floatingActionButton
constraints: MISSING
size: MISSING
alignment: Alignment.centerRight
textDirection: ltr
fit: loose
Unfortunately, this object's geometry is not known at this time, probably because it has never been laid out. This means it cannot be accurately hit-tested.
If you are trying to perform a hit test during the layout phase itself, make sure you only hit test nodes that have completed layout (e.g. the node's children, after their layout() method has been called).
at Object.throw_ [as throw] (http://localhost:61969/dart_sdk.js:5061:11)
at http://localhost:61969/packages/flutter/src/rendering/layer.dart.lib.js:4204:23
at stack.RenderStack.new.hitTest (http://localhost:61969/packages/flutter/src/rendering/layer.dart.lib.js:4209:26)
at http://localhost:61969/packages/flutter/src/rendering/layer.dart.lib.js:7665:44
at box.BoxHitTestResult.wrap.addWithPaintOffset (http://localhost:61969/packages/flutter/src/rendering/layer.dart.lib.js:7418:19)
...
So, I removed all code and kept only two text boxes and two text fields to understand what is causing the problem. But I still can't figure out the reason. Here is my simplified code for the build method of my stateless widget:
#override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.red,
title: Text("Create"),
),
body: Container(
child:Column(
children: [
//First row - Amount and Ccy labels/text boxes
Expanded(
child: Row(
children: [
Expanded(
child:Column(
mainAxisSize: MainAxisSize.max,
children: [
Text('Amount'),
TextField(),
],
)
),
Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Currency'),
TextField(),
],
)
],
)
),
//Second Row - Comment label/text box
]
)
)
);
}
I wonder if is some basic concept that I am missing here. I am testing it on Chrome.
If you use TextField inside SizedBox with the determined height it might works
After putting code i don't have this problem. is this UI the thing you wanted to achieve?
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: "title",
theme: ThemeData(primarySwatch: Colors.green),
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.red,
title: const Text("Create"),
),
body: Container(
child: Column(children: [
//First row - Amount and Ccy labels/text boxes
Row(children: [
Expanded(
child: Column(
mainAxisSize: MainAxisSize.max,
children: const [
Text('Amount'),
TextField(),
],
)),
Column(
mainAxisSize: MainAxisSize.min,
children: const [
Text('Currency'),
],
)
//Second Row - Comment label/text box
])
])),
));
}
}
I think I found the answer to the issue. When I put two textfields in a row, with the first one in an Expanded widget, flutter isn't able to compute the right width to assign for the second one because TextFields don't have any width of their own unlike Text.
So, its parent has to provide a width or flutter has to have something idea about what width to give it to that TextField. When I put both the textfields in Expanded of their own and assign a flex value to each, it works fine. Like this:
Expanded(
flex:3, //this column is thrice as wide as the second one
child: Column(
mainAxisSize: MainAxisSize.max,
children: const [
Text('Amount'),
TextField(),
],
)),
Expanded(
flex: 1,
child:Column(
mainAxisSize: MainAxisSize.min,
children: const [
Text('Currency'),
TextField(),
],
)
)
I hope this is it.

How to display a screen which contains of an Icon on top half and ListView on bottom half?

I want to display a mock-up streaming screen like this:
Top half is the video player (showing the speaker), and bottom half is a ListView displaying participants/subscribers list.
Here's my code:
import 'package:flutter/material.dart';
import 'common.dart';
class StreamingView extends StatelessWidget {
// Display a Participant item
Widget getParticipantView(Participant item) {
return Container(
padding: EdgeInsets.all(10.0),
child: Column(
children: [
Align(
alignment: Alignment.centerLeft,
child: Text(
item.name,
style: TextStyle(fontSize: 14, color: Colors.black54),
),
),
Expanded(
child: CircleAvatar(backgroundColor: Colors.blue),
),
],
));
}
// Display the participants list on a ListView
Widget getParticipantsListView(List<Participant> participantsList){
//#override
// Widget build(BuildContext context) {
return Container (
//Expanded()
height: 40,
child: ListView.builder(
itemCount: participantsList.length,
itemBuilder: (context, index){
return getParticipantView(participantsList[index]);
}
)
);
//}
}
#override
Widget build(context) {
List<Participant> theList = [
Participant(name: "Jack", description:"Away"),
Participant(name:"Paul", description:"Available"),
Participant(name:"Clive", description:"Available"),
Participant(name:"Frank", description:"Available")
];
return Scaffold(
appBar: AppBar(),
body: Container(
padding: EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Image.asset('assets/generic_portrait.jpg'),
Expanded(
flex: 1,
child: getParticipantsListView(theList)
),
],
)),
floatingActionButton: FloatingActionButton(
onPressed: () async {
print("The button is clicked...");
},
child: Icon(Icons.video_call)));
}
}
I ran it, and the result is this:
The speaker can be seen, but the participants list isn't. Turns out there's an exception:
══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY
╞═════════════════════════════════════════════════════════ The
following assertion was thrown during performLayout(): RenderFlex
children have non-zero flex but incoming height constraints are
unbounded. When a column is in a parent that does not provide a finite
height constraint, for example if it is in a vertical scrollable, it
will try to shrink-wrap its children along the vertical axis. Setting
a flex on a child (e.g. using Expanded) indicates that the child is to
expand to fill the remaining space in the vertical direction. These
two directives are mutually exclusive. If a parent is to shrink-wrap
its child, the child cannot simultaneously expand to fit its parent.
Consider setting mainAxisSize to MainAxisSize.min and using
FlexFit.loose fits for the flexible children (using Flexible rather
than Expanded). This will allow the flexible children to size
themselves to less than the infinite remaining space they would
otherwise be forced to take, and then will cause the RenderFlex to
shrink-wrap the children rather than expanding to fit the maximum
constraints provided by the parent. ... ... The relevant error-causing
widget was: Column
file:///C:/Users/anta40/Flutter/streamingtest/streaming.dart:11:16
That refers to child: Column( inside Widget getParticipantView().
How to fix this?
you can use stack , the parent maybe use column after that the stack will be the first , after that use a listview which can hold all the participants
Have you tried using Shrink-wrap in ListView.builder and remove the container with Static height.
The hight is unbound because you're using Expanded widget in the column. Remove the Expanded widget that is wrapping the CircleAvatar. Here's your code:
// Display a Participant item
Widget getParticipantView(Participant item) {
return Container(
padding: EdgeInsets.all(10.0),
child: Column(
children: [
Align(
alignment: Alignment.centerLeft,
child: Text(
item.name,
style: TextStyle(fontSize: 14, color: Colors.black54),
),
),
CircleAvatar(backgroundColor: Colors.blue),
],
));
}

SingleChildScrollView with Column of Flexible Cards: "A RenderFlex Overflowed by x pixels on bottom", How to make card expand?

I'm trying to make a list of cards that are displayed in a SingleChildScrollView.
However I can't figure out how to make the cards fit their contents.
I've attached a picture of my issue, and how I want the cards to look like.
I've tried putting them in an expanded which doesn't seem to make a difference.
I've also tried setting a manual height on the card container which for some reason only displays two cards and doesn't let me scroll.
I'm presuming that I need to set a minimum height on the cards, but I can't seem to figure out at what level should I add it.
Widget displayVideo(item) {
return Flexible(
child: Container(
child: Card(
child: Column(
children: <Widget>[
ListTile(
leading: CircleAvatar(
backgroundImage:
NetworkImage(item.fromChannel.channelThumbnail),
),
title: Text(item.fromChannel.channelTitle),
subtitle: Text(item.publishAt),
),
Container(
child: new AspectRatio(
aspectRatio: 16 / 10,
child: new Container(
decoration: new BoxDecoration(
image: new DecorationImage(
fit: BoxFit.fitWidth,
alignment: FractionalOffset.center,
image: new NetworkImage(item.thumbnailUrl),
)),
),
),
),
Container(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
item.title,
style: TextStyle(color: Colors.black, fontSize: 16),
),
),
)
],
),
),
),
);
}
Widget displayVideos(items) {
List<Widget> lines = [];
print(items);
items.videos.forEach((element) => lines.add(displayVideo(element)));
return SingleChildScrollView(
child: Container(
height: MediaQuery.of(context).size.height,
child: Column(children: lines)));
}
#override
Widget build(BuildContext context) {
final ExplorePlaylistArguments args =
ModalRoute.of(context).settings.arguments;
playlist = fetchPlaylist(args.playlistId);
return Scaffold(
appBar: AppBar(
title: Text(args.playlistName),
),
body: Container(
child: FutureBuilder<Playlist>(
future: playlist,
builder: (context, snapshot) {
if (snapshot.hasData) {
return displayVideos(snapshot.data);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return Center(child: CircularProgressIndicator());
}),
));
}
════════ Exception caught by rendering library ═════════════════════════════════════════════════════
The following assertion was thrown during layout:
A RenderFlex overflowed by 303 pixels on the bottom.
The relevant error-causing widget was:
Column file:///C:/Users/Jonathan/AndroidStudioProjects/klp_app/lib/screens/explore_playlist.dart:29:18
The overflowing RenderFlex has an orientation of Axis.vertical.
The edge of the RenderFlex that is overflowing has been marked in the rendering with a yellow and black striped pattern. This is usually caused by the contents being too big for the RenderFlex.
Consider applying a flex factor (e.g. using an Expanded widget) to force the children of the RenderFlex to fit within the available space instead of being sized to their natural size.
This is considered an error condition because it indicates that there is content that cannot be seen. If the content is legitimately bigger than the available space, consider clipping it with a ClipRect widget before putting it in the flex, or using a scrollable container rather than a Flex, like a ListView.
The specific RenderFlex in question is: RenderFlex#42b06 relayoutBoundary=up19 OVERFLOWING
... parentData: <none> (can use size)
... constraints: BoxConstraints(0.0<=w<=384.7, 0.0<=h<=67.9)
... size: Size(384.7, 67.9)
... direction: vertical
... mainAxisAlignment: start
... mainAxisSize: max
... crossAxisAlignment: center
... verticalDirection: down
◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤
════════════════════════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by rendering library ═════════════════════════════════════════════════════
A RenderFlex overflowed by 303 pixels on the bottom.
How the cards look like:
How I want each individual card to look like:
Solution:
Widget displayVideo(item) {
return Card(
child: Column(
children: <Widget>[
ListTile(
leading: CircleAvatar(
backgroundImage:
NetworkImage(item.fromChannel.channelThumbnail),
),
title: Text(item.fromChannel.channelTitle),
subtitle: Text(item.publishAt),
),
new AspectRatio(
aspectRatio: 16 / 9,
child: Image.network(item.thumbnailUrl, fit:BoxFit.fitWidth),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
item.title,
style: TextStyle(color: Colors.black, fontSize: 16),
),
)
],
),
);
}
Widget displayVideos(items) {
List<Widget> lines = [];
items.forEach((element) => lines.add(displayVideo(element)));
return SingleChildScrollView(
child: Column(children: lines));
}
Tip: You can also use ListView.builder() instead of SingleChildScrollView and Column
You have to remove Container from displayVideos method.
return SingleChildScrollView(child: Column(children: lines)); // container remove
And remove Flexible from displayVideo method.

How to make a Widget to be as small as it can (wrap_content in Android)?

I have a rendering issue with render tree similar to Column>PageView>Column, where the last Column is inside a page of the PageView.
The PageView isn't being rendered correctly, so I get an exception (Horizontal viewport was given unbounded height.) as the framework can't calculate its sizes, I can fix it by wrapping it into a Flexible or an Expanded, but I don't want the PageView to take the whole screen, I want it to be as small as possible and on the center on the screen.
Here's a representation of my problem:
// This code throws an exception:
class Widget_1_Has_Problem extends StatelessWidget {
final PageController pageController = PageController();
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(Icons.done,size: 112),
SizedBox(height: 32),
PageView(
physics: NeverScrollableScrollPhysics(),
controller: pageController,
children: <Widget>[
// Many widgets go here, I am just simplifying with a Column.
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text('TEXT TEXT TEXT TEXT TEXT TEXT'),
SizedBox(height: 16),
Text('TEXT2 TEXT2 TEXT2 TEXT2 TEXT2 TEXT2'),
],
),
],
),
],
),
);
}
}
This is what I wanted to achieve (I removed the PageView in order to show it):
class Widget_2_No_PageView extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(Icons.done,size: 112),
SizedBox(height: 32),
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text('TEXT TEXT TEXT TEXT TEXT TEXT'),
SizedBox(height: 16),
Text('TEXT2 TEXT2 TEXT2 TEXT2 TEXT2 TEXT2'),
],
),
],
),
);
}
}
And this is how I can fix it, but it's not perfect, I will show later:
class Widget_3_With_Flex_Not_Perfect_Solution extends StatelessWidget {
final PageController pageController = PageController();
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Spacer(flex: 2,),
Icon(Icons.done,size: 112),
SizedBox(height: 32),
Flexible(
flex: 1,
child: PageView(
physics: NeverScrollableScrollPhysics(),
controller: pageController,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text('TEXT TEXT TEXT TEXT TEXT TEXT'),
SizedBox(height: 16),
Text('TEXT2 TEXT2 TEXT2 TEXT2 TEXT2 TEXT2'),
],
),
],
),
),
Spacer(flex: 2,),
],
),
);
}
}
This solution isn't perfect because Spacer and Flexible or Expanded always try to maintain it's proportionality of the flex weight, which means that for smaller displays the Spacer won't vanish, it will remain there, whereas the first and desired image won't have such a void space. As we can see in the below image, the Spacer is always there. Also I have to calculate the flex factor for every change in this design, whereas in my first code example the widget will size itself to the center of the screen automatically.
How can I instruct PageView then to be as small as it can be, instead of expand as much as it wants, as that's the only solution I can find online?
The PageView uses SliverFillViewport to wrap around given children.
This SliverFillViewport doesn't care about how small the children are. It only cares how much space it can occupy from its parent. So the Flex and Align widget are useless.
Currently with PageView, it most likely not possible unless we do some calculation and use SizedBox or ConstrainedBox.
I also found this discussion
This can be done, but not with PageView. I had to use SingleChildScrollView with a Row. The reason for that is: if you want to size your PageView properly, you need to build and layout every child it has. PageView does not do that, but Row does, you can even decide how smaller elements should be positioned. PageController also works if you properly set widths of children in the row.
Note that this will only work nicely if you have small amount of pages.
class SizingPageView extends StatelessWidget {
final ScrollPhysics physics;
final PageController controller;
final List<Widget> children;
const SizingPageView({Key key, this.physics, this.controller, this.children})
: super(key: key);
#override
Widget build(BuildContext context) {
Widget transform(Widget input) {
return SizedBox(
width: MediaQuery.of(context).size.width,
child: input,
);
}
return SingleChildScrollView(
physics: physics ?? PageScrollPhysics(),
controller: controller,
scrollDirection: Axis.horizontal,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: children.map(transform).toList(),
),
);
}
}
class Solution extends StatelessWidget {
final PageController pageController = PageController();
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Spacer(
flex: 2,
),
Icon(Icons.done, size: 112),
SizedBox(height: 32),
Text('BEFORE SCROLL'),
SizingPageView(
physics: NeverScrollableScrollPhysics(),
controller: pageController,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text('TEXT TEXT TEXT TEXT TEXT TEXT'),
SizedBox(height: 16),
Text('TEXT2 TEXT2 TEXT2 TEXT2 TEXT2 TEXT2'),
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text('TEXT TEXT TEXT TEXT TEXT TEXT'),
],
),
Text('Third'),
],
),
Text('AFTER SCROLL'),
Spacer(
flex: 2,
),
FlatButton(
child: Text('Next'),
onPressed: () {
var next = pageController.page.round() + 1;
if (next >= 3) {
next = 0;
}
pageController.animateToPage(
next,
duration: Duration(seconds: 1),
curve: Curves.easeInOut,
);
},
)
],
),
);
}
}
You are asking for items inside of the PageView to set the size of PageView itself. This is not going to work with the standard class. If you look at its source, you'll find that uses Viewport inside Scrollable. Viewport grabs maximum size and ignores the size of the children (Slivers). You'll need to use a different approach or maybe create a custom PageView, perhaps one that uses ShrinkWrappingViewport.
https://api.flutter.dev/flutter/widgets/ShrinkWrappingViewport-class.html
By wrapping PageView inside SizedBox, we can get rid of the exception you are getting. (Horizontal viewport was given unbounded height.).
SizedBox(height: 32, child:
PageView(
physics: NeverScrollableScrollPhysics(),
controller: pageController,
children: <Widget>[
// Many widgets go here, I am just simplifying with a Column.
Column(
...
But that will give you a bottom overflow exception of 16 pixels since you have another SizedBox with fixed height inside Column in PageView.
In order to resolve this issue, let's just for time being replace top SizedBox with Container and add color property to it to see how much space and height is available to us.
So, instead of hardcoding the sizedbox height to 32, we can make use of MediaQuery to calculate height for us.
If you print height of the top SizedBox, it will come out to be 597
SizedBox(height: MediaQuery.of(context).size.height,
I for demo, divided the height with 5 to get 119.4 height of the SizedBox widget that contains PageView, which resolves the renderflow exception as well as maintains pageview's location at center of the screen.
If we again use Container to see now how much space and height is available to us, it will look like:
So with this approach, you will not be required to use Expanded or Flexible widgets as you mentioned and won't need to change much of your code.
The working code is as below:
h = MediaQuery.of(context).size.height / 5;
print(h); // 119.4
return Scaffold(
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(Icons.done,size: 112),
SizedBox(height: h, child:
PageView(
physics: NeverScrollableScrollPhysics(),
controller: pageController,
children: <Widget>[
// Many widgets go here, I am just simplifying with a Column.
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text('TEXT TEXT TEXT TEXT TEXT TEXT'),
SizedBox(height: 16),
Text('TEXT2 TEXT2 TEXT2 TEXT2 TEXT2 TEXT2'),
],
),
],
),
),
],
),
);
You might need to adjust height per your need, but I hope this resolves your issue and answers your question.
You can simply wrap your widget with Flexible widget https://api.flutter.dev/flutter/widgets/Flexible-class.html

children have non-zero flex but incoming height constraints are unbounded

return Card(
child: Row(
children: <Widget>[
Placeholder(
fallbackHeight: 100,
fallbackWidth: 100,
),
Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(height: 10, child: Container(child: Text("One"),)),
Expanded(child: Container(child: Text("Center") )),
],
)
],
),
);
On the code above I am getting error:
I/flutter ( 4872): The following assertion was thrown during performLayout():
I/flutter ( 4872): RenderFlex children have non-zero flex but incoming height constraints are unbounded.
I/flutter ( 4872): When a column is in a parent that does not provide a finite height constraint, for example if it is
I/flutter ( 4872): in a vertical scrollable, it will try to shrink-wrap its children along the vertical axis. Setting a
I/flutter ( 4872): flex on a child (e.g. using Expanded) indicates that the child is to expand to fill the remaining
I/flutter ( 4872): space in the vertical direction.
Whole code:
class FilmItems extends StatelessWidget {
List<String> filmListList;
List<String> _getFilmList() {
var items = List<String>.generate(101, (counter) => "item $counter");
return items;
}
FilmItems() {
filmListList = _getFilmList();
}
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: filmListList.length,
itemBuilder: (BuildContext context, int index) {
return Card(
child: Row(
children: <Widget>[
Placeholder(
fallbackHeight: 100,
fallbackWidth: 100,
),
Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(height: 10, child: Container(child: Text("One"),)),
Expanded(child: Container(child: Text("Center") )),
],
)
],
),
);
});
}
}
What is wrong?
The problem is that you are using Expanded and any of it's parents have an explicit height.
The solution would depend on how do you want to handle the height of the Expanded. In your case, seems to be that you want to have a Row with a fixed height equal to the Placeholder. In that case, you need to wrap the Row with the same height as the Placeholder, like this:
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("")),
body: ListView.builder(
itemCount: 3,
itemBuilder: (BuildContext context, int index) {
return Card(
child: SizedBox(
height: 100,
child: Row(
children: <Widget>[
Placeholder(
fallbackHeight: 100,
fallbackWidth: 100,
),
Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text("One"),
Expanded(child: Center(child: Text("Center"))),
],
),
],
),
),
);
}),
);
}
I removed the height 10 of the Text("One") because if the fontSize is bigger, the text would look cropped. And I wrapped the Text("Center") with a Center widget, I think that's what you wanted to achieve.
Suggestion: If the content inside the Row could haven a bigger height than the Row, the content would look cropped. If that could happen you might want to take another approach.
When you are using Column widget, it's parent should have a finite height. So in your code the parent is a row and it also does not have a finite height. You need wrap Column with Container and give a finite height.
Container(
height: 500,
child: Column()
)
Put your Column/Row inside an Expanded or SizedBox (with some height) like this:
Expanded(
child: Column(...)
)
Or
SizedBox(
height: 250, // give some height
child: Column(...),
)