📜  Flutter – ConstrainedBox 小部件(1)

📅  最后修改于: 2023-12-03 15:15:07.957000             🧑  作者: Mango

Flutter - ConstrainedBox Widget

ConstrainedBox is a widget in Flutter that allows you to apply constraints to another widget.

Properties
  • child: The child widget being constrained
  • constraints: The constraints that should be applied to the child widget. A BoxConstraints type is expected.
  • key: An identifier for this widget
Example
ConstrainedBox(
    constraints: BoxConstraints(
        maxWidth: 200,
        maxHeight: 200,
    ),
    child: Container(
        width: 300,
        height: 300,
        color: Colors.blue,
    ),
),

In the above example, a ConstrainedBox widget is created that constrains its child Container widget to a maximum width and height of 200 pixels each. However, the Container widget is set to have a width and height of 300 pixels, thus it overflows the defined constraints.

To see the effect of the constraints, we need to modify the child Container widget's dimensions to fit within the constraints:

ConstrainedBox(
    constraints: BoxConstraints(
        maxWidth: 200,
        maxHeight: 200,
    ),
    child: Container(
        width: 100,
        height: 100,
        color: Colors.blue,
    ),
),

Now, the Container widget's dimensions are equal to or less than the defined constraints, and so it will not overflow and will be displayed correctly within the ConstrainedBox.

Conclusion

The ConstrainedBox widget is a useful tool for ensuring that child widgets fit within specific constraints while still having flexibility in their dimensions. By defining the constraints of a ConstrainedBox, developers can ensure that its child widgets fit within these limits and display as intended.