Flutter 使用 ConstrainedBox 使控件尽可能大或尽可能小

17 min read

使用 ConstrainedBox 可以限制控件的大小,使其尽可能大或尽可能小。以下是一些示例代码:

  1. 使控件尽可能大:
ConstrainedBox(
  constraints: BoxConstraints.expand(), // 将控件的宽高限制为尽可能大
  child: Container(
    color: Colors.red,
  ),
)
  1. 使控件尽可能小:
ConstrainedBox(
  constraints: BoxConstraints(), // 不给控件设定任何限制,使其尽可能小
  child: Container(
    color: Colors.red,
  ),
)
  1. 限制控件最大宽度和最大高度:
ConstrainedBox(
  constraints: BoxConstraints(
    maxWidth: 200.0, // 最大宽度为200
    maxHeight: 200.0, // 最大高度为200
  ),
  child: Container(
    color: Colors.red,
  ),
)
  1. 限制控件最小宽度和最小高度:
ConstrainedBox(
  constraints: BoxConstraints(
    minWidth: 100.0, // 最小宽度为100
    minHeight: 100.0, // 最小高度为100
  ),
  child: Container(
    color: Colors.red,
  ),
)

以上是一些使用 ConstrainedBox 使控件尽可能大或尽可能小的示例代码,根据具体需求可以调整 constraints 的值来适应不同的场景。