Flutter开发-Layout -弹性布局(Flex和Expanded)

Flex

        Flex弹性,从字面意义可以理解具有伸缩性,它允许子Widget按照一定的比例来分配父容器的空间,在Flutter中弹性布局功能很强大,可以结合Expanded实现弹性布局.如果在已知主轴方向的情况下,使用Row或者Column会方便一些,因为这个两个Widget也是继承自Flex.

Flex({
    Key key,
    @required this.direction,
    this.mainAxisAlignment = MainAxisAlignment.start,
    this.mainAxisSize = MainAxisSize.max,
    this.crossAxisAlignment = CrossAxisAlignment.center,
    this.textDirection,
    this.verticalDirection = VerticalDirection.down,
    this.textBaseline,
    List children = const [],
  }) 

Flex中的接口属性和上篇中Row和Column几乎一样.

Expanded

Expanded可以按比例伸缩子Widget所占的空间:

const Expanded({
    Key key,
    int flex = 1,
    @required Widget child,
  }) 

        属性flex是弹性系数,如果flex=0或者=null,则子Widget没有弹性系数,如果flex大于0,则子Widget按照比例来分割主轴剩余的空间:

Column(
        mainAxisAlignment: isClick ? MainAxisAlignment.center : MainAxisAlignment.start,
        crossAxisAlignment: isClick? CrossAxisAlignment.end : CrossAxisAlignment.start,
        children: [
          Flex(
            direction: Axis.horizontal,
            children: [
              Expanded(
                flex: 1,
                child: Container(
                  height: 50.0,
                  color: Colors.red,
                ),
              ),

              Expanded(
                flex: 4,
                child: Container(
                  height: 80,
                  color: Colors.green,
                ),
              ),
            ],
          ),

          Padding(
            padding: const EdgeInsets.only(top: 30.0),
            child: SizedBox(
              height: 100.0,
              child: Flex(
                direction: Axis.vertical,
                children: [
                  Expanded(
                    flex: 2,
                    child: Container(
                      height: 60,
                      color: Colors.orange,
                    ),
                  ),
                  Spacer(
                    flex: 1,
                  ),
                  Expanded(
                    flex: 2,
                    child: Container(
                      height: 80,
                      color: Colors.purple,
                    ),
                  ),
                ],
              ),
            ),
          ),

          Text("Flutter 1",
            style: TextStyle(
              color: Colors.blueGrey,
              backgroundColor: Colors.cyan,
              fontSize: 20,
            ),
          ),

          RaisedButton(
            child: Text("RaisedButton 1",
              style: TextStyle(fontSize: 25),
            ),
            onPressed: buttonAction,
          ),

          Text("Flutter 2",
            style: TextStyle(
              fontSize: 20,
              color: Colors.green,
              backgroundColor: Colors.yellow,
            ),
          ),
        ],
      ),

你可能感兴趣的:(Flutter开发-Layout -弹性布局(Flex和Expanded))