Expanded and flexible not filling entire row - flutter

Hello I have the below code
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body:
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Row(
mainAxisSize: MainAxisSize.max,
children: [
// FlexibleWidget(),
ExpandedWidget(),
FlexibleWidget(),
],
),
Row(
children: [
ExpandedWidget(),
ExpandedWidget(),
],
),
Row(mainAxisSize: MainAxisSize.min,
children: [
FlexibleWidget(),
FlexibleWidget(),
],
),
Row(mainAxisSize: MainAxisSize.min,
children: [
FlexibleWidget(),
ExpandedWidget(),
],
),
],
),
);
}
}
class ExpandedWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Expanded(
child: Container(
decoration: BoxDecoration(
color: Colors.green,
border: Border.all(color: Colors.white),
),
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
'Expanded',
style: TextStyle(color: Colors.white, fontSize: 24),
),
),
),
);
}
}
class FlexibleWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Flexible(
child: Container(
decoration: BoxDecoration(
color: Colors.red,
border: Border.all(color: Colors.white),
),
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
'Flexible',
style: TextStyle(color: Colors.black, fontSize: 24),
),
),
),
);
}
}
And the result is this:
Shoudln't the first container fill the space left after the flexible widget is set? Since it also belongs to a column with a child of 2 expanded widgets, the column width size should be the entire screen. That means the row should be the entire screen too. I would have expected the expanded green widget in the first row to fill the row until there is no white left like the image below:
Instead it only fills half the page. Can anyone explain this behaviour?

Let me start with FlexFit before coming to the point. FlexFit.tight allows the children to fill rest of the space but FlexFit.loose allows children to size themselves as they want.
Now, as you might know Expanded is nothing but Flexible with tight-fitting i.e. fit: FlexFit.tight.
Expanded(
child: child,
)
is equivalent to
Flexible(
fit: FlexFit.tight,
child: child,
)
Now, Let's take your example.
For the first block, there are two widgets with Flex 1 (by default), which will divide the screen to two half; each will be given 50%. This does not mean that they have to take 50% of the screen. It means that they can expand to 50% of the screen. So, the Expanded widget does that. It takes 50% of the screen as it has tight-fitting.
Coming to the Flexible widget, by default, it follows loose-fitting. So it says to its children that they can expand till 50% but there is no boundation that they have to take all space. They can take whatever space they want but the upper bound is set to 50%. In your case, it only needs the space to fit "Flexible" text with some padding. So it takes that.

Pushpendra explained how flex works and why they take at most half the screen when using two flex items. However, there is no answer showing how to make one item fill the rest of the space including space that is not taken by the other item.
The trick is to only use a single flex item that takes all space (Expanded) and constraining the other item to maxWidth = half of the available width. This can be achived using LayoutBuilder to get the available width and ConstraintedBox to constrain one widget without using flex - which allows the Expanded to take more than half of the space (all that is not taken by the ConstrainedBox):
LayoutBuilder(builder: (context, constraints) {
return Row(
children: [
ConstrainedBox(
constraints: BoxConstraints(maxWidth: constraints.maxWidth * 0.5),
child: Text(
text1,
overflow: TextOverflow.fade,
softWrap: false,
),
),
Expanded(
child: Text(
text2,
overflow: TextOverflow.fade,
softWrap: false,
),
),
],
);
});

Related

Which widgets should be used for responsive UI of the following wireframe?

What widgets should be used to display 3 cartoons at the bottom of this picture and the text at the center responsively for different screen sizes?
Row with spaceEvenly
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
//your images
],
);
https://flutteragency.com/how-to-set-space-between-elements-in-flutter/
There are many ways to do this. It will also depend on what responsive behavior you are looking for. I hope, I understood your specific requirements.
Here is a solution:
class Page extends StatelessWidget {
const Page({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: AspectRatio(
aspectRatio: 16 / 9,
child: Container(
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/bg.png"),
fit: BoxFit.cover,
),
),
child: Stack(children: [
Center(
child: FractionallySizedBox(
widthFactor: .4,
child: FittedBox(
fit: BoxFit.fitWidth,
child: Text(
'Headline text',
style: GoogleFonts.chewy(
textStyle: const TextStyle(
color: Colors.white,
letterSpacing: .5,
),
),
),
),
),
),
Container(
alignment: const Alignment(0, .75),
child: FractionallySizedBox(
widthFactor: .8,
heightFactor: .3,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Image.asset("assets/images/img1.png"),
Image.asset("assets/images/img2.png"),
Image.asset("assets/images/img3.png"),
],
),
),
)
]),
),
),
);
}
}
In this solution,
I use a main Container that will have your image as background.
I then use a Stack to position the headline and the images.
The headline is Centered and defined as a FittedBox inside a FractionallySizedBox. This allows me to have responsivity for the headline too.
Finally, for the list of images, I used a FractionallySizedBox to size the list and an aligned Container to position it within the stack. The images are then spread thanks to the use of MainAxisAlignment.spaceBetween.
So, as you see, I used the following widgets to responsively size and position my Widgets:
Position
Center
Container with the alignment property
Size
FractionallySizedBox

How to make the page scrollable in the following structure (Flutter)

I'm building a product detail page. As the following piece of code and image shown, when there is a lot of content in the description part, the bottom overflow will occur. I'm wondering how to make the page scrollable, I've tried wrapping the Stack with SingleChildScrollView, but this is definitely not working in my case here. Can anyone help me with that? Thank you very much!!!!!
class DetailsScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
return Scaffold(
backgroundColor: Colors.white,
body: Stack(
children: [
buildBody("path/to/image", size),
],
),
);
}
Positioned buildBody(String imagePath, Size size) {
return Positioned.fill(
child: Column(
children: [
Expanded(
child: Container(
padding: EdgeInsets.symmetric(vertical: 60, horizontal: 30),
color: Colors.green,
child: Stack(
children: [
Align(
alignment: Alignment.center,
child: Hero(
tag: 1,
child: Image.asset(
imagePath,
width: size.width * 0.7,
),
),
),
],
),
),
),
Expanded(
child: Container(
color: Colors.white,
child: Column(
children: [
SizedBox(
height: 100,
),
Container(
margin: EdgeInsets.symmetric(
horizontal: 20,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CircleAvatar(),
SizedBox(
width: 10,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Anvesha Shandilya',
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 16),
),
Text(
'Owner',
style: TextStyle(
color: fadedBlack,
),
),
],
),
Expanded(child: Container()),
Text(
'Dec 16, 2020',
style: TextStyle(
color: fadedBlack,
fontSize: 12,
),
),
],
),
),
SizedBox(
height: 30,
),
Container(
margin: EdgeInsets.symmetric(
horizontal: 20,
),
child: Text(
'A lot of content..................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................',
style: TextStyle(
color: fadedBlack,
height: 1.7,
),
),
),
],
),
),
),
],
),
);
}
}
Error: Bottom Overflowed
To reproduce: Change the path/to/image, to this: A image can be used with the code:
tl;dr remove Expanded widgets -> remove Stack -> replace Column with ListView (for scrollability)
Start by removing Expanded widgets from the tree as you don't really need them. If possible, you should use mainAxisAlignment and crossAxisAlignment to position your widgets. That's exactly how you should handle placing the date next to user's name.
Expanded documentation states with which widgets you can use it:
Creates a widget that expands a child of a Row, Column, or Flex so
that the child fills the available space along the flex widget's main
axis.
Then remove Stack widget. If you don't then it will still work as Stack tries to get as big as its positioned children so it will just get as big as the Column you have inside. It's redundant.
Last but not least, replace Column with ListView. Column doesn't really care about whether it's overflowing or if it's being rendered. So if you create a Column that is bigger than the screen, it will simply display it which will cause the overflow. To fix that you could wrap it SingleChildScrollView, but I think it's more appropriate to just use ListView instead.
Here's an amazing explanation of layout system in Flutter: https://flutter.dev/docs/development/ui/layout/constraints

What widget should I use for center text and left-aside button

I am making layout for flutter application
What I want to do is
-----------------------
|[i] [text] |
| |
Icon should be the left (padding 5px)
And text should be the center of screen.
At first I should use the Column
However my layout is not the same proportion
It might be simple though , how can I make it??
Stack() is one of the many options that you can use. Something like this:
Stack(
children:<Widget>[
Padding(
padding: EdgeInsets.only(left: 5),
child: Icon(Icons.info),
),
Align(
alignment: Alignment.topCenter,
child: Text("I'm on the top and centered."),
),
],
),
One way you can do this is something like this..
Widget build(BuildContext context) {
return Column(
children: [
Padding(
padding: EdgeInsets.all(5),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Icon(Icons.info),
Text('text'),
Opacity(opacity: 0, child: Icon(Icons.info)),
],
),
),
Padding(
padding: EdgeInsets.all(5),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Icon(Icons.info),
Text('second text'),
Opacity(opacity: 0, child: Icon(Icons.info)),
],
),
),
],
);
}
Result:
I might be late, but I want this answer to be there, if some one would find it better for the development purposes in future time.
We can make a reusable widget, which we can use it inside the main widget. The widget will accept text, and icon to be passed when called
// IconData is the data type for the icons
Widget myWidget(String text, IconData icon) => Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
children: [
// this will be used a left-padding param
SizedBox(width: 20.0),
// using it here
Icon(icon, size: 28.0, color: Colors.greenAccent),
SizedBox(width: 5.0),
// this will take the remaining space, and then center the child
Expanded(child: Center(child: Text(text)))
]
);
To use in the main Widget, just do like this:
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// calling our widget here
myWidget('FirstText', Icons.alarm),
SizedBox(height: 20.0), // this is used as a top margin
myWidget('SecondText', Icons.notifications)
]
)
If you wanna check out the sources which I used, please see:
Expanded class
SizedBox class
The result you will get is this:
This was an answer I gave a while ago for this same issue, but the other situation was vertical (a Column) instead of horizontal (a Row). Just swap the Row and Columns out for a Column and Rows in this example and you'll get the idea.
My code has grey added in order to show the difference between the two approaches.
A Stack will work, but it's overkill for this, this kind of problem is part of why we have Expandeds and Flexibles. The trick is to use three Flexibles (2 Expandeds and a Spacer). Put the Spacer on top. It and the bottom Expanded must have the same flex value in order to center the middle Expanded.
import 'package:flutter/material.dart';
class CenteringOneItemWithAnotherItemInTheColumn extends StatelessWidget {
const CenteringOneItemWithAnotherItemInTheColumn({
Key key,
}) : super(
key: key,
);
/// Adjust these values as needed
final int sameFlexValueTopAndBottom = 40; // 40%
final int middleFlexValue = 20; // 20%
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Column Alignment Question'),
),
body: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Spacer(),
const Text(
'Cent',
style: TextStyle(
fontSize: 64,
),
),
const Spacer(),
const Text(
'Bot',
style: TextStyle(
fontSize: 64,
),
),
],
),
Column(
children: <Widget>[
/// The key is to have the Spacer and the bottom Expanded
/// use the same value for flex. That will cause the middle
/// child of the Column to be centered vertically.
Expanded(
flex: sameFlexValueTopAndBottom,
child: Container(
width: 100,
color: Colors.grey[300],
),
),
Expanded(
flex: middleFlexValue,
child: const Align(
alignment: Alignment.center,
child: Text(
'Cent',
style: TextStyle(
fontSize: 64,
),
),
),
),
Expanded(
flex: sameFlexValueTopAndBottom,
child: Container(
color: Colors.grey[300],
child: const Align(
alignment: Alignment.bottomCenter,
child: Text(
'Bot',
style: TextStyle(
fontSize: 64,
),
),
),
),
),
],
),
],
),
);
}
}

Flutter Row widget solve RenderFlex overflow by cutting off remaining area

There are a lot of questions here already about Renderflex overflow, but I believe my use case might be a bit different.
Just the usual problem - having a Widget that is too big in a Row widget, and I get the A RenderFlex overflowed by X pixels ... error.
I want to create a Row that cuts off it's overflowing child Widget if they would be rendered outside it's area without getting an error.
First off, wrapping the last element in the Row widget with Expanded or Flexible does not work in my case, as recommended here and here and many other places. Please see code and image:
class PlayArea extends StatelessWidget {
#override
Widget build(BuildContext context) {
final dummyChild = Container(
color: Colors.black12,
width: 100,
child: Text('important text'),
);
final fadeContainer = Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.centerRight,
colors: [
Colors.black26,
Colors.black87,
],
),
),
width: 600,
);
return Padding(
padding: const EdgeInsets.all(20.0),
child: Container(
color: Colors.redAccent,
child: Column(children: [
Expanded(
child: Row(
children: <Widget>[
dummyChild,
fadeContainer,
],
),
),
Expanded(
child: Row(
children: <Widget>[
dummyChild,
Expanded(
child: fadeContainer,
),
],
),
),
Expanded(
child: Row(
children: <Widget>[
Container(
color: Colors.black12,
width: 1100,
child: Text('important text'),
),
Expanded(
child: fadeContainer,
),
],
),
),
]),
),
);
}
}
Key points:
Using Expanded changes the width of Container, which changes the gradient's slope. I want to keep the gradient as it is
Even with Expanded widget, the Row is not prepared for the case when important text's area is too wide and does not fit the screen horizontally - it will get an overflow error for that Widget
it is technically working in the first case, because no red color is drawn on the right side on the green field, it 'just' has an error
How do I cut off the remaining space dynamically without any error - regardless of any screen size and content?
One solution I found is that
Row(
children: <Widget>[
dummyChild,
fadeContainer,
],
)
can be converted to
ListView(
scrollDirection: Axis.horizontal,
physics: const NeverScrollableScrollPhysics(),
children: <Widget>[
dummyChild,
fadeContainer,
],
)
Creating a horizontal list and preventing scroll on that.
edit.: just found out it that you'll get unbounded vertical height, so it's not the same.

Flutter: shrink images to fit into row while keeping aspect ratio

I would like to display two images side by side with a bit of text above and below. The layout has to work in portrait and landscape mode. The images are loaded from the network and I don't know their dimensions, although I do know the aspect ratio (3:4) and orientation (portrait).
The current solution works well in portrait mode but totally fails in landscape. Here the middle section with the two images is scaled down to fit the width which ends up with images that are too high for the space available.
[...]
#override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text('Text 1', style: Theme.of(context).textTheme.headline),
IntrinsicHeight(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: TrimmedImage(left.src, () => _advanceRight()),
),
Expanded(
child: TrimmedImage(right.src, () => _advanceLeft()),
),
],
),
),
Text('Text 2, possibly lines and lines and lines and lines and lines anlines and lines of stuff.',
style: Theme.of(context).textTheme.title,
textAlign: TextAlign.center,
),
],
),
);
}
[...]
class TrimmedImage extends StatelessWidget {
final String src;
final onTap;
TrimmedImage(src, this.onTap);
#override
Widget build(BuildContext context) {
return AspectRatio(
aspectRatio: 3.0 / 4.0,
child: ConstrainedBox(
constraints: BoxConstraints.expand(),
child: Container(
decoration: new BoxDecoration(
border: new Border.all(
color: Colors.grey,
width: 2.0,
),
borderRadius:
new BorderRadius.circular(10.0),
),
child: GestureDetector(
onTap: onTap,
child: ClipRRect(
borderRadius: new BorderRadius.circular(8.0),
child: CachedNetworkImage(
placeholder: CircularProgressIndicator(),
errorWidget: Icon(Icons.broken_image),
imageUrl: src ?? '',
fit: BoxFit.cover,
),
),
),
),
),
);
}
In Landscape mode I'd like the images to be scaled down (while keeping the aspect ratio) to fit the height of the available space, rather than the width.
Portrait mode currently looks good on a big screen but I suspect it'd also fail if the screen were too small to fit the height of all 3 components.
Create your own layout with a CustomMultiChildLayout and, specifically, a MultiChildLayoutDelegate. The Flutter Shrine demo is a good example: https://github.com/flutter/flutter/blob/master/examples/flutter_gallery/lib/demo/shrine/shrine_home.dart. See the _Heading and _HeadingLayout classes.