第二章●第三节:容器(Container)

容器组件我们可以比喻成一个菜篮子,我们可以将我们喜欢的蔬菜放到里面。但其并不是一个菜篮子,它在绘制过程中,首先应用给定的矩阵变换,然后绘制装饰以填充范围,接着绘制子组件,最后绘制foregroundDecoration,同时填充范围。
没有子组件的容器若无限制约束(这种情况,其会尽可能小)则试图尽可能大。有子组件的容器使用子组件尺寸适应自身。同时也可以用宽度,高度,和约束条件属性来控制。

布局行为:

  • 如果容器没有子组件,没有设置高度,没有设置宽度,没有约束条件,并且父组件提供无限制约束,则容器尝试尽可能小;
  • 如果容器没有子组件且没有对齐方式,但提供了高度,宽度或约束条件,则按照给定条件组合后容器尽可能小;
  • 如果容器没有子组件,没有高度,没有宽度,没有约束条件,没有对齐方式,但是父组件提供了有界约束,则容器会扩展以适应父组件提供的约束;
  • 如果容器具有对齐方式,并且父组件提供无限制约束,则容器会尝试围绕子组件调整自身大小;
  • 如若,容器具有子组件但没有高度,没有宽度,没有约束,也没有对齐,并且容器将约束从父组件传递给子组件并调整其大小以匹配子组件;
  • 边距和填充属性也会影响布局。

官网示例一:在中心位置显示一个48*48的小绿块。

import 'package:flutter/material.dart';

void main() => runApp(myApp());
//在中心显示一个48*48的小绿块
class myApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Text("Container 组件"),
        ),
        body: Center(
          child: Container(
            margin: const EdgeInsets.all(10.0),
            color: Colors.green,
            width: 48.0,
            height: 48.0,
          ),
        ),
      ),
    );
  }
}

《第二章●第三节:容器(Container)》 中心小绿块

官网示例二:使用Container各类属性绘制一个图

import 'package:flutter/material.dart';

void main() => runApp(exampleTwo());


class exampleTwo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Text("Container 组件"),
        ),
        body: Center(
          child: Container(
            constraints: BoxConstraints.expand(
              height: Theme.of(context).textTheme.display1.fontSize * 1.1 + 200.0
            ),
            padding: EdgeInsets.all(8.0),
            color: Colors.teal.shade700,
            alignment: Alignment.center,
            child: Text(
              "Hello World",
              style: Theme.of(context).textTheme.display1.copyWith(color: Colors.white),
            ),
            foregroundDecoration: BoxDecoration(
              image: DecorationImage(
                image: NetworkImage("https://www.example.com/images/fram.png"),
                centerSlice: Rect.fromLTRB(270.0, 180.0, 1360.0, 730.0)
              )
            ),
            transform: Matrix4.rotationZ(0.1),
          ),
        ),
      ),
    );
  }

}

《第二章●第三节:容器(Container)》 各类属性绘制容器

Container组件

《第二章●第三节:容器(Container)》 Container组件

本节内容到此结束,若在使用过程中遇到问题,欢迎留言交流,我们一起成长。

总目录结构

    原文作者:ohayoi
    原文地址: https://www.jianshu.com/p/4df6e9d19d85
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞