首頁 > 軟體

Flutter系列重學Container範例詳解

2023-01-20 14:02:01

一、Container 簡介

flutter 開發中最核心的是用最少的元件(層次)完成功能開發;Container 前端的盒子模型實現,類似 div 標籤,掌握其他元件前,深入學習理解 Container 的使用是必要的。

Container是一個組合類容器,由DecoratedBoxConstrainedBox、TransformPaddingAlign等元件組合的一個多功能容器,所以我們只需通過一個Container元件可以實現同時需要裝飾、變換、約束限制的場景。

二、範例

  • 範例包含透明度,背景裝飾,前景裝飾,child 模糊度,紅色部分是 child;

buildSection() {
  return Opacity(
    opacity: 1,
    child: Container(
      margin: EdgeInsets.all(20),
      padding: EdgeInsets.all(20),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(20)),
        gradient: LinearGradient(
          colors: [Colors.green, Colors.yellow],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.red.withOpacity(0.5),
            spreadRadius: 5,
            blurRadius: 7,
            offset: Offset(0, 3), // changes position of shadow
          ),
        ],
        image: DecorationImage(
          image: NetworkImage('https://tenfei02.cfp.cn/creative/vcg/800/new/VCG21409037867.jpg'),
          fit: BoxFit.cover,
        ),
      ),
      foregroundDecoration: BoxDecoration(
        color: Colors.yellow,
        border: Border.all(color: Colors.green, width: 5),
        borderRadius: BorderRadius.all(Radius.circular(400)),
        image: DecorationImage(
          image: NetworkImage('https://pic.616pic.com/bg_w1180/00/04/08/G5Bftx5ZDI.jpg'),
          fit: BoxFit.cover,
        ),
      ),
      child: BackdropFilter(
        filter: ui.ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
        child: Container(
          constraints: BoxConstraints.expand(),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(20)),
            color: Colors.red,
          ),
          child: Text('VCG21409037867'),
        ),
      ),
    ),
  );
}
  • 實現背景圖 background-repeat 顯示,flutter支援四種型別:
enum ImageRepeat {
  repeat,
  repeatX,
  repeatY,
  noRepeat,
}

這裡以第一種 ImageRepeat.repeat 為例:

Container(
  decoration: BoxDecoration(
    image: DecorationImage(
      image: AssetImage('images/img_update.png'),
      repeat: ImageRepeat.repeat,
      alignment: Alignment.topLeft,
    )
  ),
  child: Container(
    constraints: BoxConstraints.expand(),
    child: OutlinedButton(
      onPressed: () { print("ImageRepeat.repeat"); },
      child: Text('ImageRepeat.repeat',
        style: TextStyle(fontWeight: FontWeight.bold, color: Colors.red),
      ),
    ),
  ),
),

transform && alignment

Container(
  decoration: BoxDecoration(
    image: DecorationImage(
      image: AssetImage('images/img_update.png'),
      repeat: ImageRepeat.repeat,
      alignment: Alignment.topLeft,
    )
  ),
  transform: Matrix4.rotationZ(.2),//變化
  alignment: Alignment.centerRight, //卡片文字對齊
  child: Text(
    "5.20", style: TextStyle(color: Colors.red, fontSize: 40.0),
  ),
),

三、原始碼分析

class Container extends StatelessWidget {
  Container({
    Key? key,
    this.alignment,
    this.padding,
    this.color,
    this.decoration,
    this.foregroundDecoration,
    double? width,
    double? height,
    BoxConstraints? constraints,
    this.margin,
    this.transform,
    this.transformAlignment,
    this.child,
    this.clipBehavior = Clip.none,
  }):super(key: key);
  // 子項
  final Widget? child;
  // 內邊距
  final EdgeInsetsGeometry? padding;
  // 背景色,和 decoration 只能二選一
  final Color? color;
  // 背景裝飾
  final Decoration? decoration;
  // 前景裝飾(在 child 之上)
  final Decoration? foregroundDecoration;
  // 約束條件
  final BoxConstraints? constraints;
  // 外邊距
  final EdgeInsetsGeometry? margin;
  // 變化
  final Matrix4? transform;
  // 變化之後  child 對齊方式
  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!;
  }
  ...
}

原始碼很簡單,元件層層包裹,但是我們必須清楚每一個引數的作用和使用場景。它可以幫你用更少的層級完成功能,這很重要。

以上就是Flutter系列重學Container範例詳解的詳細內容,更多關於Flutter重學Container的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com