I have a Flutter widget like this, with a SingleChildScrollView
inside a Column
inside a parent container:
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.grey,
borderRadius: BorderRadius.circular(10),
),
child: const Column(
children: [
Text("Widget title"),
SingleChildScrollView(
child: Text(
"This is a long piece of text that may or may not fit the screenn"
"This is a long piece of text that may or may not fit the screenn"
"This is a long piece of text that may or may not fit the screenn"
"This is a long piece of text that may or may not fit the screenn"
"This is a long piece of text that may or may not fit the screenn"
"This is a long piece of text that may or may not fit the screenn",
),
),
],
),
);
}
}
I want to nest that inside another column like this:
Scaffold(
appBar: ...
body: Column(
children: [
Text('Short Text 1'),
SizedBox(height: 20),
Text('Short Text 2'),
SizedBox(height: 20),
MyWidget(),
SizedBox(height: 20),
Text('Short Text 3'),
SizedBox(height: 20),
Text('Short Text 4'),
],
),
)
But, the scroll view never scrolls. When the text is too long to fit all the screen, the bottom half of the column gets cut off and I get an overflow error.
Some other answers said to wrap both MyWidget()
and the SingleChildScrollView()
in Expanded()
s. That works great when the text is long, but when the text is short, my widget still expands to take all the available room, which is not the effect I want
Is there any way to get the scroll view inside MyWidget
to shrink as much as needed to fit everything on the screen and expand to take up available room, but not expand to take up more room than it can fill?
Edit: To be clear, I want the extra whitespace (if there is any) to be at the end of the column, as it would be if there were no flexible/scroll components.
3
Answers
Use Flexible instead of Expanded.
https://api.flutter.dev/flutter/widgets/Flexible-class.html
We can do that by removing SingleChildScrollView, changing Column to ListView, and setting shrinkWrap to true. (MyWidget)
On another column, just wrap MyWidget with Flexible
Short Content
Long Content
Example Code
Use
Flexible
to wrapMyWidget
andSingleChildScrollView
then set mainAxisSizeColumn
inMyWidget
tomainAxisSize: MainAxisSize.min
instead of default value (MainAxisSize.max
) and let theColumn
fills the remaining space.Wrap with
Flexible
Wrap with
Flexible
and setmainAxisSize
tomin
to preventColumn
from using all remaining space for short text.For long text