Efficient way to make container take remaining width in a Row widget in Flutter - flutter

I am new to Flutter and was practicing its UI where I came across a situation where I had a list where each list element have an image on the left and some text on right.
Below is my approach to that
child: ListView(
padding: const EdgeInsets.symmetric(horizontal: 20),
children: [
const SizedBox(height: 5),
Row(
children: [
Container(
height: 80,
width: 80,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
image: const DecorationImage(
image: NetworkImage('http://images.unsplash.com/photo-1555010133-d883506aedee?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max'),
fit: BoxFit.cover
)
),
),
const SizedBox(width: 10),
Container(
color: Colors.green,
height: 80,
width: 280,
)
],
),
],
),
Here I am specifying width individually for both containers which is not an efficient way to do this since phone sizes may vary.
Below is the result for above block of code
Screenshot of the app screen
I tried specifying crossAxisAlignment: CrossAxisAlignment.stretch to the Row() but it throws an error as below
The following assertion was thrown during performLayout():
BoxConstraints forces an infinite height.
How can I achieve this? Please assist
Thank you

Wrap the widget with an Expanded inside the row:
Row(
children: [
...otherChildren,
Expanded(
child: Container(
color: Colors.green,
height: 80,
),
),
],
),

Use ListView.builder with ListTile widgets. It has a leading widget (normally an icon or an avatar) to the left, text in the middle and trailing widget (normally an icon), each of which is optional.
ListView.builder(
itemCount: ...,
itemBuilder: (BuildContext context, int index) {
return ListTile(
leading: const CircleAvatar(
radius: 20.0,
foregroundImage: NetworkImage(...),
),
title: Text(...),
subtitle: Text(...),
trailing: ...,
onTap: () => ...,
);
},
)

Related

Flutter ListTile leading height

I'd like to have a listtile where the leading widget is simply a half-transparent white container. Let me clarify it with an example
I managed to create the layout above (2 ListTile's). But as you can see, when the title property contains a large text as it is doing in the first (the green) tile, the height of the leading widget is not following as it should. The below code returns a ListTile given a Label which is a class of my own that simply contains text, textcolor and backgroundcolor.
ListTile(
contentPadding: EdgeInsets.zero,
dense: true,
minLeadingWidth: 15,
tileColor: label.bgColor,
textColor: label.textColor,
horizontalTitleGap: 0,
minVerticalPadding: 0,
trailing: getPopUpMenuButton(label),
leading: Container(
height: double.maxFinite,
width: 15,
color: Colors.white54,
),
title: Padding(
padding: EdgeInsets.all(4),
child: Text(
label.title,
),
),
)
So to summarize: how to make the leading height follow the height of the ListTile?
ListTile provide the UI with specific rules. As for leading this Size is defined within the source code as
final BoxConstraints maxIconHeightConstraint = BoxConstraints(
//...
maxHeight: (isDense ? 48.0 : 56.0) + densityAdjustment.dy,
);
final BoxConstraints looseConstraints = constraints.loosen();
final BoxConstraints iconConstraints = looseConstraints.enforce(maxIconHeightConstraint);
final double tileWidth = looseConstraints.maxWidth;
final Size leadingSize = _layoutBox(leading, iconConstraints);
final Size trailingSize = _layoutBox(trailing, iconConstraints);
The height is coming from
maxHeight: (isDense ? 48.0 : 56.0) + densityAdjustment.dy,
We can create the custom widget using rows and column,
body: Center(
child: ListView.builder(
itemCount: 33,
itemBuilder: (context, index) => Padding( //use separate builder to and remove the padding
padding: const EdgeInsets.all(8.0),
child: Container(
width: double.infinity,
decoration: BoxDecoration(
color: Colors.green,
borderRadius:
BorderRadius.circular(defaultBorderRadiusCircular),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
SizedBox(
width: 20,
),
Expanded(
child: Container(
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: Colors.cyanAccent,
borderRadius: BorderRadius.only(
bottomRight:
Radius.circular(defaultBorderRadiusCircular),
topRight:
Radius.circular(defaultBorderRadiusCircular),
)),
child: Row(
children: [
Expanded(
child: Text(
"I managed to create the layout above (2 ListTile's). But as you can see, when the title property contains a large text as it is doing in the first (the green) tile, the height of the leading widget is not following as it should. The below code returns a ListTile given a Label which is a class of my own that simply contains text, textcolor and backgroundcolor.",
softWrap: true,
maxLines: 13,
style: TextStyle(),
),
),
Icon(Icons.menu),
],
),
),
),
],
),
),
),
),
),

I tried to wrap column with Singlechildscrollview Flutter but screen goes blank

[enter image description here][1]
Inside My column, there is a stack, a carousel slider,a gridview builder. I want to scroll all of them together. I tried to use singlechildscrollview as you can see in the code below. Please Someone help me how can I scroll those things together.
[1]: https://i.stack.imgur.com/FYexC.png` enter code here`
Scaffold(
backgroundColor: Colors.orange,
// Color(0xFFFFF176),
body: SingleChildScrollView(
child: Column(
children: [
Expanded(
child: Stack(
alignment: Alignment.bottomCenter,
children: [
CarouselSlider(
items: slideImage
.map((image) =>
Builder(builder: (BuildContext context) {
return Container(
height: 200,
width: 500,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(40),
image: DecorationImage(
image: AssetImage(image),
fit: BoxFit.fill),
),
);
}))
.toList(),
options: CarouselOptions(
onPageChanged: (index, reason) {
setState(() {
activeIndex = index;
});
},
height: 300,
viewportFraction: 1,
autoPlay: true,
),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: AnimatedSmoothIndicator(
activeIndex: activeIndex, count: slideImage.length),
),
],
),
),
SizedBox(
height: 10,
),
Expanded(
child: GridView.builder(
shrinkWrap: true,
// physics: NeverScrollableScrollPhysics(),
itemCount: menuImage.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 0.8,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
),
itemBuilder: (context, index) => Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
color: Color(0xFFFFFDE7),
elevation: 10,
child: GridTile(
child: Column(
children: [
Image.asset(
menuImage[index],
fit: BoxFit.fill,
),
Text(
title[index],
style: TextStyle(fontSize: 18),
),
],
),
),
),
),
),
],
),
),
);
}
}
It would be best if you gave height to the column you are using singlechildeScrollview.
Wrap column widget in container or sizedbox widget and give it height.
column widget has children widget GridView.builder that is wrapped in expanded so gridview.builder will try to take all available height in the column which will be infinite because it's not defined and you will get column covering screen taking infinite screen height in short blank screen.
In flutter, Column will take height as much as it can, SingleChildScrollView child dont have height (infinite). Combine together, Flutter don't know how to render them correctly and causing error.
To solve it, try to determine the height of Column by widgget like SizedBox or determine the mainSize.min.
Another way to solve it is wrap Column by IntrinsicHeight but not recommend cause it heavy.
If it takes too much height. so give height to the column.
like this..
SingleChildScrollView(
child: SizedBox(
height: 500,
child: Column(
children: const [...],
),
),
)
your expanded widget is taking whole space of column try removing it or replacing it with Sizedbox.

Flutter | How to fill the remaining space of a ListView?

In my Flutter app, I have a ListView:
return Scaffold(
body: SafeArea(
child: Container(
color: Colors.blueAccent,
child: ListView(
children: [
Container(
color: Colors.yellow,
height: 100
),
const SizedBox(height: 10),
// How to make this container fill up the remaining height?
Container(
color: Colors.black,
),
],
),
),
),
);
This produces the following view:
Question: How can I make the second box (with black background color) fill up the remaining space? If the content of the box exceeds the remaining space, the ScrollView will enable scrolling.
Is this possible?
There is a better option here using SliverFillRemaining in combination with CustomScrollView instead of a ListView
in your case the code will look like this.
Container(
color: Colors.blueAccent,
child: CustomScrollView(
shrinkWrap: true, // or false
slivers: <Widget>[
SliverToBoxAdapter(
child:Container(
color: Colors.yellow,
height: 100
),),
SliverToBoxAdapter(
child: SizedBox(height: 10),),
// use SliverFillRemaining to make this container fill up the remaining height?
SliverFillRemaining(
hasScrollBody: false, // if using a column, so the widgets in it, doesn't scroll
child:Container( //this container will fill the remaining space in the ViewPort
color: Colors.black,
),
) ,
],
),
),
Fill the remaining space of a ListView means filling the infinite height. I will prefer using Stack as body in this case, hope you can simply archive this.
How can we do without stack?
In this case, we can get the height and use it on Column and using Expanded on inner child that will fill the remaining spaces even for dynamic height.
I prefer using LayoutBuilder to get height.
body: LayoutBuilder(builder: (context, constraints) {
return SafeArea(
child: Container(
color: Colors.blueAccent,
child: ListView(
children: [
SizedBox(
// 1st child of listView
height: constraints.maxHeight,
child: Column(
children: [
Container(color: Colors.yellow, height: 100),
const SizedBox(height: 10),
Expanded(
child: Container(
color: Colors.black,
),
),
],
),
)
],
),
),
);
}),
You can get size and then set a proportion for each...
And set NeverScrollableScrollPhysics() to ensure no slight scrolling, as per below this appears to get what you are seeking.
Widget build(BuildContext context) {
Size _size = MediaQuery.of(context).size;
return Container(
child: Scaffold(
body: SafeArea(
child: Container(
color: Colors.blueAccent,
child: ListView(
physics: NeverScrollableScrollPhysics(),
children: [
Container(color: Colors.yellow, height: _size.height * 0.20),
SizedBox(height: _size.height * 0.10), // How to make this container fill up the remaining height?
Container(
height: _size.height * 0.70,
color: Colors.black,
),
],
),
),
),
));
}
}
Try below code hope its helpful to you. use MediaQuery here. add MediaQuery height to your black container
Refer blog also here for relative to screen size
Container(
color: Colors.blueAccent,
child: ListView(
shrinkWrap: true,
physics: ScrollPhysics(),
children: [
Container(
color: Colors.yellow,
height: 100,
),
const SizedBox(height: 10),
// How to make this container fill up the remaining height?
Container(
color: Colors.black,
height: MediaQuery.of(context).size.height,
),
],
),
),
Your result screen->

How to arrange the items correctly in flutter

I try to make design of page of display comment. I need make page design is as follows: list at up and then Text Field at the bottom.So user will can see all comment and send new comment.
Something like photo:
but I have same problem with display.
This is my code:I make it like that now but now I can see list just without text field at the bottom
#override
Widget build(BuildContext context) {
return FutureBuilder<List<Flowerdata>>(
future: fetchFlowers(),
builder: (context, snapshot) {
if (!snapshot.hasData) return Center(
child: CircularProgressIndicator()
);
return ListView(
children: snapshot.data
.map((data) => Column(children: <Widget>[
GestureDetector(
onTap: ()=>{
getItemAndNavigate(data.id, context)
},
child: Row(
children: [
Container(
width: 100,
height: 100,
margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
child: ClipRRect(
borderRadius: BorderRadius.circular(8.0),
child:
Image.network(data.flowerImageURL,
width: 200, height: 100, fit: BoxFit.cover,))),
Flexible(child:
Text(data.flowerName,
style: TextStyle(fontSize: 18))
),
]),),
Divider(color: Colors.black),
],))
.toList(),
);
Container(
width: 280,
padding: EdgeInsets.all(10.0),
child: TextField(
controller: naameController,
autocorrect: true,
decoration: InputDecoration(hintText: 'Enter Your Name Here'),
)
);
},
);
}
How can I arrange the items correctly?
First, your Container widget is unreachable, you should fix it then you can wrap your widgets with Column and wrap ListView with Expanded widget after giving height to Container. It will fix your problem.
But i have some suggestions about ListView. Why you did not use ListView.separated? If you use separated method you can delete map and your Divider.
Also when i looked your design, your list items looks like a card. You can use Card widget beside of GestureDetector.
I hope this will help you, if not i will glad to help you.
Edit: Here is sample code based on your question and my answer;
Column(
children: [
Expanded(
child: ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int i) {
InkWell(
onTap: () => getItemAndNavigate(snapshot.data[i].id, context),
child: Card(
child: Row(
children: <Widget>[
Container(
width: 100,
height: 100,
margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
child: ClipRRect(
borderRadius: BorderRadius.circular(8.0),
child: Image.network(snapshot.data[i].flowerImageURL,
width: 200, height: 100, fit: BoxFit.cover,),
),
),
Flexible(
child: Text(
snapshot.data[i].flowerName,
style: TextStyle(fontSize: 18),
),
),
]
),
),
);
},
),
),
Container(
width: 280,
padding: EdgeInsets.all(10.0),
child: TextField(
autocorrect: true,
decoration: InputDecoration(hintText: 'Enter Your Name Here'),
),
),
],
),
You are placing the TextField in the position after returning ListView, which make it dead code. You can add it at the end of your ListView children list or place a Stack outside to place both the ListView and TextField inside.

Widget which adjusts to the children size?

Is there a widget in Flutter which adjusts itself on the content of it's children which are in Rows and Columns?
I can't seem to find anything related, and I am constantly hit with infinite overflows errors.....
As an example, lets say I would have 3 Widgets in a Row, 1 of which is a text, which I cannot guess how long it will be, but I need to expand the parent as much as the widget needs and at the sametime wrap the text
I would have something like:
Row(
children: [
Expanded(child: Widget1(....)),
Expended(child: Text(.....)),
Expanded(child: Widget2(....))
]
)
Right?
I would want the parent of the row to expand as much as it needs for the children to be shown, I want to align Widget1 and Widget2 in different ways (1-center, 2-bottom).
If I put them in Column I can center Widget1, but I cannot put Widget2 at the bottom because if I put Column to max size it overflows, if I don't it doesn't align...
How would you do it?
I really don't understand the logic behind the inifnite layout thing....
For example, here is where I am stuck at the moment.
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
color: Global.findCategory(event.categId).color.withAlpha(150),
blurRadius: 20,
spreadRadius: -20,
offset: Offset(0, 5)
)
],
color: Colors.white,
borderRadius: BorderRadius.circular(30)
),
child: Row(
children: <Widget>[
Align(
alignment: Alignment.center,
child: Padding(
padding: const EdgeInsets.all(5.0),
child: Container(
width: Global.scaleSmallDevice(context) * 64,
height: Global.scaleSmallDevice(context) * 64,
decoration: BoxDecoration(
shape: BoxShape.rectangle,
borderRadius: BorderRadius.circular(10),
image: DecorationImage(
fit: BoxFit.cover,
image: event.image
)
)
),
)
,
),
Flexible(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
CustomText(
text: title,
color: Global.findCategory(event.categId).color,
fontSize: 16,
),
Flexible(
child: CustomText(
text: shortInfo,
color: Global.findCategory(event.categId).color,
fontSize: 12,
),
)
],
),
),
Stack(
alignment: Alignment.bottomCenter,
children: <Widget>[
Align(
alignment: Alignment.bottomCenter,
child: StatefulBuilder(
builder: (context, setState) {
IconData buttonIcon = (event.favorite) ? Icons.favorite : Icons.favorite_border;
return SplashButton(
splashColor: Global.findCategory(event.categId).color,
child: Icon(buttonIcon, color: Global.findCategory(event.categId).color, size: 30),
onTap: () async {
await event.setFavorite(context);
setState(() {
buttonIcon = (event.favorite) ? Icons.favorite : Icons.favorite_border;
});
}
);
},
),
),
],
),
),
],
);
}
In this case I want the StatefulBuilder widget to be on the bottom and the entire container be as small as the column with the CustomText widgets.
The widget with image inside I want it to be centered, while the text to be fully available to the user.
If I don't add a Column as Container, it goes as the height allows it and the StatefulBuilder widget center itself at the bottom, in the curent code it's at the center.....
Sorry if I'm not coherent, it's a bit late and I am tired after coding all day and stuck at this widget for a few hours.