Flutter Container尺寸的确定

Container 简介

Container 官方教程

Container 是一个结合了尺寸,形状,背景颜色,间距,留白,装饰等功能于一身的组件。

class Container extends StatelessWidget {
  Container({
    Key? key,
    //子组件对齐方式
    this.alignment,
    //内边距
    this.padding,
    //背景颜色,不能和decoration同时设置
    this.color,
    //背景修饰 添加形状,阴影边框,渐变色填充等,位于child 的下面
    this.decoration,
    //前景修饰 添加形状,阴影边框,渐变色填充等,位于child 的上面面
    this.foregroundDecoration,
    //Container的宽度
    double? width,
    //Container的高度
    double? height,
    //布局约束,约束child组件的最大尺寸和最小尺寸,同时Container自身的尺寸也可能会受影响
    BoxConstraints? constraints,
    //外边距
    this.margin,
    //变形参数,缩放,平移,旋转
    this.transform,
    //指定了变换,则相对于容器大小的原点对齐方式
    this.transformAlignment,
    this.child,
    //剪裁方式
    this.clipBehavior = Clip.none,
  }) : assert(margin == null || margin.isNonNegative),
       assert(padding == null || padding.isNonNegative),
       assert(decoration == null || decoration.debugAssertIsValid()),
       assert(constraints == null || constraints.debugAssertIsValid()),
       assert(clipBehavior != null),
       assert(decoration != null || clipBehavior == Clip.none),
       assert(color == null || decoration == null,
         'Cannot provide both a color and a decoration\n'
         'To provide both, use "decoration: BoxDecoration(color: color)".',
       ),
       constraints =
        (width != null || height != null)
          ? constraints?.tighten(width: width, height: height)
            ?? BoxConstraints.tightFor(width: width, height: height)
          : constraints,
       super(key: key);

  final Widget? child;
  final AlignmentGeometry? alignment;
  final EdgeInsetsGeometry? padding;
  final Color? color;
  final Decoration? decoration;
  final Decoration? foregroundDecoration;
  final BoxConstraints? constraints;
  final EdgeInsetsGeometry? margin;
  final Matrix4? transform;
  final AlignmentGeometry? transformAlignment;
  final Clip clipBehavior;

  EdgeInsetsGeometry? get _paddingIncludingDecoration {
    if (decoration == null || decoration!.padding == null)
      return padding;
    final EdgeInsetsGeometry? decorationPadding = decoration!.padding;
    if (padding == null)
      return decorationPadding;
    return padding!.add(decorationPadding!);
  }

  @override
  Widget build(BuildContext context) {
    Widget? current = child;

    if (child == null && (constraints == null || !constraints!.isTight)) {
      current = LimitedBox(
        maxWidth: 0.0,
        maxHeight: 0.0,
        child: ConstrainedBox(constraints: const BoxConstraints.expand()),
      );
    }

    if (alignment != null)
      current = Align(alignment: alignment!, child: current);

    final EdgeInsetsGeometry? effectivePadding = _paddingIncludingDecoration;
    if (effectivePadding != null)
      current = Padding(padding: effectivePadding, child: current);

    if (color != null)
      current = ColoredBox(color: color!, child: current);

    if (clipBehavior != Clip.none) {
      assert(decoration != null);
      current = ClipPath(
        clipper: _DecorationClipper(
          textDirection: Directionality.maybeOf(context),
          decoration: decoration!,
        ),
        clipBehavior: clipBehavior,
        child: current,
      );
    }

    if (decoration != null)
      current = DecoratedBox(decoration: decoration!, child: current);

    if (foregroundDecoration != null) {
      current = DecoratedBox(
        decoration: foregroundDecoration!,
        position: DecorationPosition.foreground,
        child: current,
      );
    }

    if (constraints != null)
      current = ConstrainedBox(constraints: constraints!, child: current);

    if (margin != null)
      current = Padding(padding: margin!, child: current);

    if (transform != null)
      current = Transform(transform: transform!, alignment: transformAlignment, child: current);

    return current!;
  }

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(DiagnosticsProperty('alignment', alignment, showName: false, defaultValue: null));
    properties.add(DiagnosticsProperty('padding', padding, defaultValue: null));
    properties.add(DiagnosticsProperty('clipBehavior', clipBehavior, defaultValue: Clip.none));
    if (color != null)
      properties.add(DiagnosticsProperty('bg', color));
    else
      properties.add(DiagnosticsProperty('bg', decoration, defaultValue: null));
    properties.add(DiagnosticsProperty('fg', foregroundDecoration, defaultValue: null));
    properties.add(DiagnosticsProperty('constraints', constraints, defaultValue: null));
    properties.add(DiagnosticsProperty('margin', margin, defaultValue: null));
    properties.add(ObjectFlagProperty.has('transform', transform));
  }
}

Container 尺寸的确定

在没有子组件的情况 (child = null)

首先在结合父组件传递的约束和Container自身的width,height,constraints属性计算约束

  1. 如果计算出来的约束时有界的,则尽量占满
Scaffold(
        appBar: AppBar(title: const Text('这是Flutter练习')),
        body: LayoutBuilder(builder: (_, cons) {
          print(cons);// BoxConstraints(0.0<=w<=411.4, 0.0<=h<=635.4)
          return Container(color: Colors.red);
        }),
 )
Screenshot_1653721972.png
  1. 如果计算出来的约束时无界的,则尽量缩小 常见的无边界的组件有Row(水平无边界) 和 Column(垂直无边界)
 Scaffold(
        appBar: AppBar(title: const Text('这是Flutter练习')),
        body: Column(
          children: [
            LayoutBuilder(builder: (_, cons) {
              print(cons); // BoxConstraints(0.0<=w<=411.4, 0.0<=h<=Infinity)
              return Container(color: Colors.red);
            })
          ],
        ),
      )
Screenshot_1653722170.png

在有子组件的情况(child 不为null)

首先将父组件传递的约束和Container自身的width,height,constraints约束传递给子组件,子组件可以确定自身的尺寸

  1. 如果没有设置对其(alignment)方式的请情况下,Container会尽可能的小,以便匹配child的尺寸
Scaffold(
        appBar: AppBar(title: const Text('这是Flutter练习')),
        body: Column(
          children: [
            LayoutBuilder(builder: (_, cons) {
              print(cons); // BoxConstraints(0.0<=w<=411.4, 0.0<=h<=Infinity)
              return Container(
                color: Colors.red,
                child: Container(color: Colors.green, width: 100, height: 100),
              );
            })
          ],
        ),
      )
Screenshot_1653722537.png
  1. 如何设置对齐(alignment)方式,但是某个纬度的约束时无界的化,Container还是在会无界约束的维度尽可能的小,以便匹配child的尺寸
Scaffold(
        appBar: AppBar(title: const Text('这是Flutter练习')),
        body: Column(
          children: [
            LayoutBuilder(builder: (_, cons) {
              // 在y轴方向无界,所以高度尽可能的小,但是x轴上是有界的,会尽可能的大
              print(cons); // BoxConstraints(0.0<=w<=411.4, 0.0<=h<=Infinity)
              return Container(
                alignment: Alignment.center,
                color: Colors.red,
                child: Container(color: Colors.green, width: 100, height: 100),
              );
            })
          ],
        ),
      )
Screenshot_1653722858.png
  1. 如何设置对齐(alignment)方式,约束是有界的,Container会尽可能的放大,为对齐方式创造条件

     Scaffold(
            appBar: AppBar(title: const Text('这是Flutter练习')),
            body:LayoutBuilder(builder: (_, cons) {
              print(cons); //  BoxConstraints(0.0<=w<=411.4, 0.0<=h<=635.4)
              return Container(
                alignment: Alignment.center,
                color: Colors.red,
                child: Container(color: Colors.green, width: 100, height: 100),
              );
            }),
          )
    
Screenshot_1653723182.png

margin ,padding,decoration 也是会对Container的尺寸产生影响的

margin 会直接增加Container的尺寸,而padding和decoration(设置了边框等)只有在Container试图匹配child的尺寸时额外增加尺寸

总结

在没有child的情况下,有界约束越大越好,无界约束越小越好,在有child的情况下,没有对齐越小越好,有对齐无界,越小越好,有对齐有界,越大越好

你可能感兴趣的:(Flutter Container尺寸的确定)