Within my layout, I have a Row. On the left side of that Row, I have a Column containing two Text objects of differing font sizes. On the right side of the Row, I have an Image. I want the Image to scale itself uniformly to have an equal height to the intrinsic height of the Column on the left side of the Row. I want this to work whether the Image's pixel height is lesser or greater than the intrinsic height of the Column, regardless of the font sizes used in the Text widgets and the text scaling factor used by the operating system. (That is, I don't want to hard-code the Image size.)
How can I make this work? I suspect I may need to cloak the Image in some widget to make its parent think it has an intrinsic height of 0 because Images have intrinsic heights equal to their pixel heights.
Here is some broken code I tried in DartPad:
(Note: the network image is the same image used in the documentation # https://flutter.dev/docs/cookbook/images/network-image . I don't have any rights to it.)
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: IntrinsicHeight(
child: Container(
color: Colors.green,
width: 600,
height: 600,
child: Row(crossAxisAlignment: CrossAxisAlignment.end, children: [
Column(children: [
Text("Larger", style: TextStyle(fontSize: 36)),
Text("Smaller", style: TextStyle(fontSize: 18))
]),
Expanded(
child: Image.network(
"https://picsum.photos/250?image=9",
alignment: Alignment.bottomRight,
fit: BoxFit.scaleDown,
))
]),
),
)));
}
}
Related
I tried my best to summarize what I want in the title, but here is a more detailed explanation:
Widgets' centers should be placed evenly throughout the row.
A larger widget should be able to extend into the "personal space" of a smaller one.
When it would overflow, overflow should start on the bigger items, cutting into the smaller ones later.
Here's an illustration:
Behavior with Expandeds:
Everything fits
Longest item is overflowing - The problem with this is that the longest text would easily fit if it could extend into the boundary of the shorter texts next to it.
How it should work:
Please notice: The boxes are not Expanded, but the centers of them are evenly placed (not by themselves, but as if they were the centers of Expandeds). As opposed to just laying them out with usual MainAxisAlignment options; neither of those ensures that the centers are evenly placed, a longer text can push the shorter ones to one side. (Illustraion of what I don't want)
Everything fits
Longest text extends into the area of the shorter ones
When two boxes would touch, overflow the longer one
Extreme case - default to even sizes
This may be asking a lot, but I think there should be a way of achieving these, what's more, I think this should be the default way rows with texts work.
Any help on any sub-request is much appreciated.
Edit: I understand that everything I described is pretty complicated when put together. I would be happy to know a way to just simply place center lines evenly, with different width boxes (and no, spaceEvenly doesn't do this). Overflowing behavior can be a different question.
Have you tried mainAxisAlignment: MainAxisAlignment.spaceEvenly? Then you can play with the padding. It seems that you would also like to make your UI responsive, try the LayoutBuilder class. The documentation can be found here https://flutter.dev/docs/development/ui/layout/responsive .
First of all use 3 Expanded() for taking spaces for 3 Text() Widgets after that you can align your text at center using a container. Hope this solution will meet your requirement.
import 'package:flutter/material.dart';
final Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Container(
alignment: Alignment.center,
child: Text('Lorem', style: TextStyle(fontSize: 24),),
),
),
Expanded(
child: Container(
alignment: Alignment.center,
child: Text('Lorem ispum', style: TextStyle(fontSize: 24),),
),
),
Expanded(
child: Container(
alignment: Alignment.center,
child: Text('Lorem', style: TextStyle(fontSize: 24),),
),
),
]
);
}
}
As far as I see, Column and ListView both have a very distinct usage when used for a base root layouting.
Column is used when the screen has few components (such as login screen). We can add some Expanded components to adjust white spaces in between, so when the keyboard is visible, the screen shrink to keep everything visible.
ListView is used when the screen has many components that potentially need scrolling. We can't use Expanded component in ListView. When using ListView, appearing keyboard does not change the white spaces, only change the size of outer ListView, while the inner content is wrapped in scroll view.
Now the problem is, how if I want to have screen like this:
When all the contents' combined vertical size is not longer than available height quota given from parent (in this case, screen's height), then the components behave like inside Column: expanding or shrinking to fill available white spaces according to rules set by Expanded.
When all the content's combined vertical size is longer than available height quota, then the components behave like inside ListView: all the possible expanding components will shrink into their minimum size (ignoring Expanded), and the screen is scrollable so user can see the rest of the screen below.
Is this possible to be done in Flutter? How?
EDIT: based on Reign's comment, I have isolated some code from SingleChildScrollView manual, but it looks like it still can't handle if its children contains Expanded.
Widget columnRoot({
MainAxisAlignment mainAxisAlignment = MainAxisAlignment.spaceBetween,
AssetImage backgroundImage,
List<Widget> children
}) =>
LayoutBuilder(builder: (BuildContext context, BoxConstraints viewportConstraints) =>
SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: viewportConstraints.maxHeight,
),
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: backgroundImage,
fit: BoxFit.cover),
color: Colors.white
),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: mainAxisAlignment,
children: children
),
)
)
)
);
Widget content(BuildContext context) => columnRoot(children: [
Container(color: Colors.red, height: 100.0),
Expanded(Container(color: Colors.green)), // without this line, there's no layout error
Container(color: Colors.blue, height: 100.0),
]);
Error:
RenderFlex children have non-zero flex but incoming height constraints are unbounded.
I added some code you can test with also with some explanation.
Copy paste and run the code
class MyWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: SingleChildScrollView( //Since setting it to scrollable, your widget Column with expanded children wont work as it supposed to be because it wont know its parent height
//Since its already scrollable `Expanded` will expand or shrink now based on it child widget (Expanded(child: SomeHeight widget)) refer: #10 example
child: IntrinsicHeight( //This will fix the expanded widget error
child: Container(
//Test remove this height
// height: 400, //But when you set its height before its parent scroll widget, `Expanded` will expand based on its available space
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.max,
children: [
Container(color: Colors.red, height: 100.0),
//#10
//Experiment with this
Expanded(
child: Container(
color: Colors.purple,
// height: 100.0, //initialized height, remove parent container height: 400
// child: Text("This is also considered as min height"),
),
),
Container(color: Colors.blue, height: 100.0),
],
),
),
),
),
),
);
}
}
I have a layout where I want to expand a widget (container) to the right, it's the red area in the examples. To the left of the expanded container there is a column with an image at the topleft (blue in examples) and a button in the bottom of the column. I do know the button width, it's a bit over 100 pixels but we can assume that it's 100 pixels if that helps.
The thing is that the blue area (it's a user uploaded image) can vary in size. From e.g. 100x100 to 800x800. It will be square and smaller than 100x100 is not supported. Large images are resized to 800x800.
I want to achieve this:
The column should adapt it's size depending on the image size.
The column should be as wide as needed by the button but otherwise 100 <= width <= 400 depending on image size.
The column should not overflow in any direction.
The red area should be maximized.
The button should always be at the bottom left of the layout.
I cannot know the column height in advance without using a LayoutBuilder and I want to know if this is achievable without calculating the exact height in pixels using a LayoutBuilder.
Here's an example of how I want it too look with a small image (100x100) and that works with the code below the image:
Code that works well for 100x100 image:
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(widget.title)),
body: Center(
child: Container(
height: 400,
width: 800,
child: Row(
children: <Widget>[
_buildColumn(),
Expanded(child: Container(color: Colors.red)),
],
),
),
),
);
}
Widget _buildColumn() {
return Container(
constraints: BoxConstraints(maxWidth: 400),
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
_buildImage(),
MaterialButton(
color: Colors.green,
child: Text('Fixed height button'),
onPressed: () {},
)
],
),
),
);
}
Widget _buildImage() {
// This can vary from 100x100 to 800x800 (always square)
var size = 100.0;
return Container(color: Colors.blue, width: size, height: size);
}
If I bump it to an 800x800 image by changing the size variable to 800.0 in _buildImage() I get this layout:
I understand that the column have unconstrained height on it's children so it will render the blue container with 800px height which creates the overflow. I do know that the column height is 400px in this case and that the button is 48px high so I can calculate that the max image size is 352px in height. By wrapping the blue container in a Container with constraints (maxWidth: 352, maxHeight: 352) I achieve the layout that I want:
Widget _buildImage() {
// This can vary from 100x100 to 800x800 (always square)
var size = 800.0;
return Container(
constraints: BoxConstraints(maxWidth: 352, maxHeight: 352),
child: Container(color: Colors.blue, width: size, height: size),
);
}
I can also achieve this using expanded, like this:
Widget _buildImage() {
// This can vary from 100x100 to 800x800 (always square)
var size = 800.0;
return Expanded(
child: Container(color: Colors.blue, width: size, height: size),
);
}
I want to avoid using calculated pixels for height/width so lets continue with the Expanded widget. When I have that expanded widget with a small image, i.e. 100x100 I get this result (which is not what I want):
I need to align my blue square within the expanded widget to prevent it to getting stretched but when I do that (align top left), like this:
Widget _buildImage() {
// This can vary from 100x100 to 800x800 (always square)
var size = 100.0;
return Expanded(
child: Container(
alignment: Alignment.topLeft,
child: Container(color: Colors.blue, width: size, height: size),
),
);
}
Then I get this result:
The container outside of the blue container expands and makes the column unnecessary wide. I want to have the same look as the first image when I have a small image.
How can I achieve this adaptive layout without using a LayoutBuilder and calculating exact image constraints?
Wrap the column with a container and set the height:
MediaQuery.of(context).size.height * 0.8;
it will contain 80% height in screen
child:Column(
children: <Widget>[
Container(
height: double.infinity,
width: 100.0,
color: Colors.red,
child: Text('hello'),
),)
in this,when i make height:double.infinity,it gives error in run saying **BoxConstraints forces an infinite height.**but when i give height manually it work fine.
can anyone explain me why this happening.
How about this one.
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
children: <Widget>[
Expanded(
child: Container(
// height: double.infinity,
width: 100.0,
color: Colors.red,
child: Text('hello'),
),
),
],
),
),
);
}
}
This means that you can't offer inifite height to the container. It's obvious behaviour if you don't provide the contraints to height.
You have to specify limited height to the container so that flutter can render it, if you offer it infinite it how can flutter render that and up to which constraints it would do that !
Rather you can set double.infinity to width and flutter will successfully render that because by default flutter has constraints for width it will set width to width of screen.
Considering that you have to provide height as that of screen you can use MediaQuery for that
Widget yourMethod(or build)(BuildContext context){
final screenHeight = MediaQuery.of(context).size.height;
return Column(
children:<Widget>[
Container(
height:screenHeight,//but this will be height of whole screen. You need to substract screen default paddings and height of appbar if you have one
width:100.0,
....
)
]);
}
Hope this helps !
Happy coding..
BoxConstraints forces an infinite height
Why This Happens
You're asking to render an infinite height object without a height constraint... Flutter can't do that.
Column lays out children in two phases:
Phase 1: non-Flex items (anything not Expanded, Flexible or Spacer)
done in unconstrained space
Phase 2: Flex items (Expanded,Flexible, Spacer only)
done with remaining space
Phase 1
Column's phase 1 vertical layout is done in unbounded space. That means:
no vertical constraint → no height limit
any widget with infinite height will throw the above error
you can't render an infinite height object in an infinite height constraint... that's goes on forever
Phase 2
after Phase 1 widgets have taken as much space as they intrinsically need, phase 2 Flex items share the remaining/leftover space
the remaining space is calculated from incoming constraints minus Phase 1 widgets dimensions
double.infinity height will expand to use up the remaining space
Infinite Height is OK
Here's an example of using infinite height on a Container inside a Column, which is fine:
class ColumnInfiniteChildPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: [
Flexible(
child: Container(
height: double.infinity, // ← perfectly fine
child: Text('Column > Container > Text')),
),
Text('Column > Text')
],
),
),
);
}
}
Remove the Flexible and the error will be thrown.
I have a Container where I need to show a barcode and I'd love to have the barcode to be as wide as possible on the screen.
For now I set the font size at a reasonable size that suits all devices, but it's only temporary of course.
How can I solve this? This is the code I am using for building the Widget.
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_title),
),
body: Container(
padding: const EdgeInsets.all(12.0),
child: Column(
children: <Widget>[
SizedBox(
width: double.infinity,
child: Text(_barcode, style: TextStyle(fontFamily: 'Code128', fontSize: 90.0))
),
Text(_barcode, style: TextStyle(fontSize: 40.0))
]
),
)
);
}
I believe what you're looking for is FittedBox.
BoxFit applies whichever 'fit' you want to stretch/scale the child to fit in the box. It doesn't perform a pure 'stretch' on the text but rather the space it should take up. You shouldn't specify the text's size at the same time.
That looks like this:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
MyAppState createState() {
return new MyAppState();
}
}
class MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Center(
child: Container(
color: Colors.blue,
width: 300.0,
height: 200.0,
child: FittedBox(
fit: BoxFit.contain,
child: Text("Whee"),
),
),
),
),
),
);
}
}
If you're wanting to actually 'stretch' the text (i.e. make the actual characters wider or taller) you'll have to do something a bit more custom.
If that's the case, look at CustomPaint, CustomPainter, TextPainter, and the Canvas translate & scale options. Basically, you would need to create a class extending CustomPainter in which you created a TextPainter, laid it out at a particular size, painted it onto the canvas, and then scaled it to fit the actual size of the CustomPainter (or do you scale the canvas first - I forget...). Then you'd pass an instance of that class to CustomPaint.
FittedBox is what worked for me but there is a twist. I also had to style my fontSize to a big number for it to work. Hope this helps.
child: FittedBox(
fit: BoxFit.fitHeight,
child: Text(
"Your Expanded Text :)",
style: TextStyle(fontSize: 400.0),
),
),
The code sample in the question has a Text widget as one of the children: of a Column widget. The width of the Text parent is unknown.
So to maximise the width and size of the Text widget in this case, wrap the Text widget in a FittedBox, then an Expanded.
child: Column(children: <Widget>[
Expanded(
child: FittedBox(
fit: BoxFit.contain,
child: Text(
'123',
)),
),
]),
The Text size should also automatically resize correctly even when the device is rotatated, or the screen resized, without overflow issues.
Expanded:
/// A widget that expands a child of a [Row], [Column], or [Flex]
/// so that the child fills the available space.
///
/// Using an [Expanded] widget makes a child of a [Row], [Column], or [Flex]
/// expand to fill the available space along the main axis (e.g., horizontally for
/// a [Row] or vertically for a [Column]). If multiple children are expanded,
/// the available space is divided among them according to the [flex] factor.
from /flutter/packages/flutter/lib/src/widgets/basic.dart
FittedBox:
/// Creates a widget that scales and positions its child within itself according to [fit].
you can use fitted box widget.
FittedBox(child:Text('text sample'));
https://api.flutter.dev/flutter/widgets/FittedBox-class.html
FittedBox would only work if it is provided some constraints, so make sure to provide one, like provide height as shown below:
SizedBox(
height: 400, // 1st set height
child: FittedBox(child: Text("*")), // 2nd wrap in FittedBox
)
Use TextPainter.width and a for loop to find the largest fitting font size (adding +1 is not very efficient, you may want to fine-tune that):
import 'package:flutter/material.dart';
main() => runApp(MaterialApp(
home: MyHomePage(),
theme: ThemeData(platform: TargetPlatform.iOS),
));
class MyHomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Text autoscale'),
),
body: Padding(
padding: EdgeInsets.all(32.0),
child: Center(
child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
final text = 'Hello World';
final style = TextStyle(fontWeight: FontWeight.bold); // apply your barcode font here
final fontSize = calculateAutoscaleFontSize(text, style, 30.0, constraints.maxWidth);
return Text(
text,
style: style.copyWith(fontSize: fontSize),
maxLines: 1,
);
},
),
),
),
);
}
}
double calculateAutoscaleFontSize(String text, TextStyle style, double startFontSize, double maxWidth) {
final textPainter = TextPainter(textDirection: TextDirection.ltr);
var currentFontSize = startFontSize;
for (var i = 0; i < 100; i++) {
// limit max iterations to 100
final nextFontSize = currentFontSize + 1;
final nextTextStyle = style.copyWith(fontSize: nextFontSize);
textPainter.text = TextSpan(text: text, style: nextTextStyle);
textPainter.layout();
if (textPainter.width >= maxWidth) {
break;
} else {
currentFontSize = nextFontSize;
// continue iteration
}
}
return currentFontSize;
}
Wrap the text within a FittedBox widget, to force the text to be enclosed by a box. The FittedBox's size will depend on it's parent's widget. Within the FittedBox, the Text widget, can simply 'cover' the box, so the text doesn't stretch to fill the available space within the FittedBox. The enum BoxFit.fill, is a way to stretch the text to fit the entire space available within the FittedBox. You can change the dimensions of the box by altering the height and width of the FittedBox's parent, the Container.
Container(
height: _height,
width: _width,
FittedBox(
fit: BoxFit.fill,
child: Text("Whee"),
)
)