Flutter 基礎佈局Widgets之Align詳解

若數發表於2019-05-03

概述

一般來說,Align的使用都是其他控制元件的一個引數,目的是為了設定子child的對齊方式,比如居中,左上,右下等多個對齊方向,其本身用法也多靈活。

建構函式

const Align({
    Key key,
    this.alignment = Alignment.center,
    this.widthFactor,
    this.heightFactor,
    Widget child
  })
複製程式碼
  • alignment 設定對齊方向,使有多種使用方式: 比如:FractionalOffset(0.5, 0.5) == Alignment(0.0,0.0) == Alignment.center ,都是將子child居中對齊的控制方式 Alignment(0.0,0.0)表示矩形的中心。從-1.0到+1.0的距離是矩形的一邊到另一邊的距離。 而Alignment中還可以這樣使用對齊方式的控制,也是較為常用的使用方式:
  /// The top left corner.
  static const Alignment topLeft = Alignment(-1.0, -1.0);

  /// The center point along the top edge.
  static const Alignment topCenter = Alignment(0.0, -1.0);

  /// The top right corner.
  static const Alignment topRight = Alignment(1.0, -1.0);

  /// The center point along the left edge.
  static const Alignment centerLeft = Alignment(-1.0, 0.0);

  /// The center point, both horizontally and vertically.
  static const Alignment center = Alignment(0.0, 0.0);

  /// The center point along the right edge.
  static const Alignment centerRight = Alignment(1.0, 0.0);

  /// The bottom left corner.
  static const Alignment bottomLeft = Alignment(-1.0, 1.0);

  /// The center point along the bottom edge.
  static const Alignment bottomCenter = Alignment(0.0, 1.0);

  /// The bottom right corner.
  static const Alignment bottomRight = Alignment(1.0, 1.0);
複製程式碼

即本質就是類似於語法糖將各個方向的對齊方式簡單封裝了下。 FractionalOffset(1, 1) 類似Alignment() 但是座標起點是左上角,且範圍為0~1 比如 FractionalOffset(0.5, 0.5) 代表中間位置

  • widthFactor 如果非空,則將其寬度設定為子元素的寬度乘以該因子,可以大於或小於1.0,但必須是正數。
  • heightFactor 如果非空,則將其高度設定為子元素的高度乘以該因子,可以大於或小於1.0,但必須是正數。

示例程式碼

// align

import 'package:flutter/material.dart';

class AlignLearn extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text('Align')
      ),
      // 對齊小部件
      body: Align(
          // Alignment(0.0,0.0)表示矩形的中心。從-1.0到+1.0的距離是矩形的一邊到另一邊的距離。
          // alignment: Alignment(1, 0),
          // FractionalOffset(1, 1) 類似Alignment() 但是座標起點是左上角,且範圍為0~1 比如 FractionalOffset(0.5, 0.5) 代表中間位置
          alignment: Alignment.bottomRight,
          child: Container(
            color: Colors.blueAccent,
            width: 100,
            height: 100,
          ),
      ),
    );
  }
}
複製程式碼

示例效果

38AB9A013729BA2F5AD366131691A548.png

相關文章