Flutter入门-溢出容器

114 阅读1分钟

OverflowBox

class OverflowBox extends SingleChildRenderObjectWidget {
  const OverflowBox({
    Key key,
    this.alignment = Alignment.center,  // 对齐方式
    this.minWidth,                      // 允许最小宽度
    this.maxWidth,                      // 允许最大宽度
    this.minHeight,                     // 允许最小高度
    this.maxHeight,                     // 允许最大高度
    Widget child,
  })
}

如果OverflowBox不设置约束,那么OverflowBox将使用他父控件的约束;如果OverflowBox的子控件尺寸大于OverflowBox父控件,且OverflowBox的约束也大于OverflowBox父控件,这时候OverflowBox子项就会溢出显示。
需要注意的是OverflowBox自己是没有宽高的,他的属性都是对子控件的约束而已,OverflowBox的尺寸是由他的父控件约束来决定的。这一点跟SizedOverflowBox是不一样的。

Alignment

  • Alignment.topLeft = Alignment(-1.0, -1.0):
  • Alignment.topCenter = Alignment(0.0, -1.0):
  • Alignment.topRight = Alignment(1.0, -1.0):
  • Alignment.centerLeft = Alignment(-1.0, 0.0):
  • Alignment.center = Alignment(0.0, 0.0):
  • Alignment.centerRight = Alignment(1.0, 0.0):
  • Alignment.bottomLeft = Alignment(-1.0, 1.0):
  • Alignment.bottomCenter = Alignment(0.0, 1.0):
  • Alignment.bottomRight = Alignment(1.0, 1.0):
  • Alignment()
  • Alignment.lerp()
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('OverflowBox'),
      ),
      body: Container(
        color: Colors.blue,
        height: 200,
        child: OverflowBox(
          alignment: Alignment.topCenter,
          minWidth: 20,
          maxWidth: 200,
          maxHeight: 400,
          minHeight: 20,
          child: Container(
            width: 50,
            height: 300,
            color: Colors.amber,
          ),
        ),
      ),
    );
  }

image.png

SizedOverflowBox

SizedOverflowBox 组件的特点是:

    1. 它可以指定自身特定的尺寸
    1. 它会将原始的约束传递给孩子
    1. 它的孩子可以溢出

OverflowBox组件也可以允许子组件溢出,他们最大的区别在于: OverflowBox 会指定新约束传递给孩子,而 SizedOverflowBox 则将原始约束传递给孩子 如下,在一个灰色盒子左上角,有一个小红圈,其中心与盒子左上角对齐。可以看出在效果上,小红圈 溢出了灰色盒子的区域。实现方式是,灰色盒子内部对齐方式 Alignment.topLeftSizedOverflowBox 对齐方式 Alignment.center

class CustomSizedOverflowBox extends StatelessWidget{
  
  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.topLeft,
      color: Colors.grey.withAlpha(88),
      width: 50,
      height: 50,
      child: buildChild(),
    );
  }

  Widget buildChild() {
    return SizedOverflowBox(
      alignment: Alignment.center,
      size: Size.zero,
      child: Container(
        decoration: const BoxDecoration(
          color: Colors.red,
          shape: BoxShape.circle,
        ),
        width: 15,
        height: 15,
      ),
    );
  }
}