Flutter – ConstrainedBox Widget
Last Updated :
26 Sep, 2022
ConstrainedBox is a built-in widget in flutter SDK. Its function is to add size constraints to its child widgets. It comes quite handy if we want a container or image to not exceed a certain height and width. It is also good to keep text in a wrapped layout by making the Text widget a child on ConstrainedBox. This functionality can also be found in SizedBox widget or else.
Constructor of ConstrainedBox Class:
ConstrainedBox(
{Key key,
@required BoxConstraints constraints,
Widget child}
)
Property of ConstrainedBox Widget:
- constraints: This property takes in the BoxConstrain Class as the object. It puts constraints it’s child widget using the functions of the BoxConstraints class.
Example 1:
Dart
import 'package:flutter/material.dart' ;
void main() {
runApp(
MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text( 'GeeksforGeeks' ),
backgroundColor: Colors.greenAccent[400],
centerTitle: true ,
),
body: Center(
child: ConstrainedBox(
constraints: BoxConstraints.expand(height: 200, width: 200),
child: Container(
color: Colors.green,
),
),
),
),
),
);
}
|
Output:
Explanation: In this flutter application we can see that the ConstrainedBox Widget is used to constrain the height and width of its child widget which is a Container. Here we have used BoxConstraints.expanded with the height and width parameter set to 200. We can notice that the height and width parameters are not mentioned in the Container widget it just expands to fill its parent widget.
Example 2:
Dart
import 'package:flutter/material.dart' ;
void main() {
runApp(
MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text( 'GeeksforGeeks' ),
backgroundColor: Colors.greenAccent[400],
centerTitle: true ,
),
body: Center(
child: ConstrainedBox(
constraints: BoxConstraints.expand(height: 200, width: 200),
child: Text(
'A Computer Science portal for geeks. It contains well
written,well thought and well explained computer science
and programmingarticles, quizzes, interview experiences
and much more.',
style: TextStyle(fontSize: 15),
),
),
),
),
),
);
}
|
Output:
Explanation: In this flutter app the ConstrainedBox widget is used to wrap the text in a 200 X 200 box. Here also the text expands to fill the box as BoxConstraints.expand is used. This application of ConstrainedBox widget is very helpful when we want our text to not spill out of a certain bounded area.
Share your thoughts in the comments
Please Login to comment...