I have created a customWidget for showing data named CustomShowDataWidget, and this widget is used in many screens but with different available heights.. so how to apply height based on available screen height…
here is my custom widget
class ShowTransactionWidget extends StatelessWidget {
ShowTransactionWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
height: 500,//-< I have given fixed height what I dont want...
color: Colors.grey.shade200,
child: Column(
children: [
Align(
child: Text('Recent Transactions',style: TextStyle(
color: Colors.blue,
fontSize: 20
),),
alignment: Alignment.centerLeft,
),
Expanded(
child: ListView.builder(
itemCount: 100,
itemBuilder: (context,index){
return ListTile(
title: Text('Hello $index'),
);
}),
)
],),
);
}
}
here is the one of the screen where I am using this widget
class NextScreen extends StatelessWidget {
const NextScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(children: [
Container(
color: Colors.blue,
height: MediaQuery.of(context).size.height*0.70,
),
ShowTransactionWidget(),
],),
);
}
}
2
Answers
Try the following code:
You want your widget
ShowTransactionWidget
to have a height which is relative to the available height given to it.Okay, first, you must learn that in flutter, Constraints go down. Sizes go up. Parent sets position. So if your widget can be a part of other widgets, don’t always expect it can take the size you want it to take.
After you learn that, you have multiple options:
LayoutBuilder
widget to wrap yourContainer
. This widget will give you the available constraints to your widget, and you can use the max height to determine the height of your widget.MediaQuery
to get the size inside yourShowTransactionWidget
, but you may want more information than the size of the screen as your widget might not be allowed to have the whole size of the screen, so this option might not fit all cases.ShowTransactionWidget
in its constructor, and then define the height of theContainer
relative to that heightCustomSingleChildLayout
.