@universal
2019-11-06T10:58:01.000000Z
字数 1790
阅读 423
flutter
flutter中的widget类似于View基类, widgetstate类似于view的controller,为view提供数据以及逻辑处理,包括对view的管理。
在 Dart 语言中使用下划线前缀标识符,会 强制其变成私有。
Dart
var/object/dynamic 修饰任何类型
var赋值后不能修改类型
object 是所有类型的父类,命名的变量只能调用object类中的方法
dynamic 类似于 oc里的 id
1、row/column的溢出
row/column都会在主轴方向上尽可能大的布局,即在主轴上尽可能完全的展示child,但是在副轴上会根据对应的约束,为child设置约束。
2、若container设置了宽高,则child设置的宽高将不生效。
body: Container(
width: 300,
height: 300,
color: Colors.black,
child: Container(
width: 50,
height: 50,
color: Colors.red,
child: Container(
width: 10,
height: 10,
color: Colors.blue,
)
)
)
本来这段代码期望是这样的效果
但是实际运行是这样:
之前的container相关使用的基础知识就不概述了,可自行查阅相关资料。
container实际绘制的大小不仅仅跟构造方法里设置的宽高有关,还跟设置的约束BoxConstraints有关。
我们看下Container的入口
直接看最重要的constraints:
constraints =
(width != null || height != null) // (1)
? constraints?.tighten(width: width, height: height) //(2)
?? BoxConstraints.tightFor(width: width, height: height) //(3)
: constraints,
按照最开始的代码来看, 我们传入了width和height,所以条件1过,进入条件2。条件2里的constraints是我们构造方法里的constraints,因为没有传所以?.过滤掉进入条件3,这里的??是判断当前container对象的constraints(并不是构造方法里的那个)是否为空,如果为空,则调用BoxConstraints.tightFor方法,这里因为是父container,外部没有给它传约束进来所以是空的。
我们看BoxConstraints.tightFor(width: width, height: height)方法
那这个方法很明显,为container1创建了一个(minWidth = width, minHeight = height, maxWidth = width, maxHeight = height)的约束。相当于将这个container1的宽高彻底固定为传入的width、height。
ok,继续看下一步,container1如何约束它的child。主要在container的build方法。
经过人工校验,我们可以直接进入这个if条件
if (constraints != null)
current = ConstrainedBox(constraints: constraints, child: current);
这是不是很明显,为child套上了一层约束,也就是为container2套上了一层ConstrainedBox,那我们的container2在绘制的时候就会带上这个constraints。所以不管container2设置的宽高是多少,都是在当前的约束下,展示成与container1一样的大小。
那修改下源码验证下(不推荐这么做):
return UnconstrainedBox(child: current);
在build方法的返回值中套上一层UnconstrainedBox,抵消掉设置的约束。可以看到结果:
解决方案:
(1)在child外部套上一层UnconstrainedBox。抵消约束。
(2)或者给child套一层row或者column
利用row/column会重新为children设置约束。如下图。即设置副轴上的maxHeight或者maxWidth。这样children就可以按照自己的宽高显示。