I want my container to be automatically have adjusted height based on content inside, however whenever I remove the height, it disappears completely. How can I sort this out?
Padding(
padding: const EdgeInsets.fromLTRB(20.0, 0, 20.0, 0),
child: Container(
width: double.infinity,
height: 150,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/texture.jpg'),
fit: BoxFit.cover)),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
DefaultText(fontSize: 16, weight: FontWeight.bold, textData: 'Test'),
Text("12.09.2011")
],
),
SizedBox(height: 16.0),
Expanded(child:
DefaultText(fontSize: 16, weight: FontWeight.normal, textData: 'Test ')
),
],
),
),
),
)
CodePudding user response:
Try wrapping your Container with an Expanded widget
Column(
children: [
Expanded(
child: Container(
//...
),
),
],
),
Containers in Flutter take the height of their parent widget when you don't give them a height.
Note that your Padding widget is redundant here as you can add padding or margin to the Container
Here's your code with the Expanded widget and without the unnecessary Padding widgets
Column(
children: [
Expanded(
child: Container(
margin: const EdgeInsets.fromLTRB(20.0, 0, 20.0, 0),
padding: const EdgeInsets.all(8.0),
width: double.infinity,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/texture.jpg'),
fit: BoxFit.cover),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
DefaultText(
fontSize: 16,
weight: FontWeight.bold,
textData: 'Test'),
Text("12.09.2011")
],
),
SizedBox(height: 16.0),
Expanded(
child: DefaultText(
fontSize: 16,
weight: FontWeight.normal,
textData: 'Test '),
),
],
),
),
),
],
)
Keep in mind that the Expanded widget above will throw an error if you wrap your Column widget with a scrollable widget like a SingleChildScrollView widget because then the Column will not have a size and thus the Expanded widget will not know the height it will expand to and thus, throw an error. In this case you will have to assign a height
CodePudding user response:
Judging by what it looked like when I ran your code, an alternative would be to use a Stack widget:
Stack(children: [
Image(image: AssetImage('assets/images/texture.jpg')),
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Test'),
Text("12.09.2011")
],
),
SizedBox(height: 16.0),
Expanded(child:
Text('Test ')
),
],
),
),
])
