decoration
与 foregroundDecoration
有点像css中::before
和::after
,区别是绘制顺序不同,foregroundDecoration
可以用来装饰前景
// 使用decoration去设置 Container( color: Colors.yellow, alignment: Alignment.center, margin: EdgeInsets.all(10), child: Container( padding: EdgeInsets.fromLTRB(100, 20, 100, 20), transform: Matrix4.rotationZ(0.2), decoration: BoxDecoration( image: DecorationImage( image: NetworkImage('https://static.daojia.com/assets/project/tosimple-pic/icon-about-us_1587887989775.png'), alignment: Alignment.center, ), ), child: Text( "快狗打车快狗打车", textDirection: TextDirection.ltr, style: TextStyle(color: Colors.black), ), ), )
// 使用foregroundDecoration去设置 Container( color: Colors.yellow, alignment: Alignment.center, margin: EdgeInsets.all(10), child: Container( padding: EdgeInsets.fromLTRB(100, 20, 100, 20), transform: Matrix4.rotationZ(0.2), foregroundDecoration: BoxDecoration( image: DecorationImage( image: NetworkImage('https://static.daojia.com/assets/project/tosimple-pic/icon-about-us_1587887989775.png'), alignment: Alignment.center, ), ), child: Text( "快狗打车快狗打车", textDirection: TextDirection.ltr, style: TextStyle(color: Colors.black), ), ), )
效果对比:
可以看到,使用foregroundDecoration
设置背景图时,背景图图片会盖在文字上方,使用decoration
则相反
使用constraints
来设置约束,用来约束自身,描述当前widget所允许占用的空间大小,通常使用BoxConstraint
来设置约束条件。这里约束了子Container
的最大和最小宽高
child Container无child的情况下,子Container
会使用约束允许的最大高度和最大宽度,
Container( color: Colors.yellow, alignment: Alignment.centerLeft, child: Container( color: Colors.green, constraints: BoxConstraints( maxHeight: 300, maxWidth: 300, minHeight: 100, minWidth: 100 ), ), );
child Container有child的情况,子Container
会根据它的child的大小和约束来布局,本例中由于Text
文本widget所占用的空间并未达到约束规定的最小空间,即最小宽高,这里直接按照约束中的最小宽高进行布局
Container( color: Colors.yellow, alignment: Alignment.centerLeft, child: Container( color: Colors.green, constraints: BoxConstraints( maxHeight: 300, maxWidth: 300, minHeight: 50, minWidth: 100 ), child: Text( "快狗打车", textDirection: TextDirection.ltr, style: TextStyle(color: Colors.black), ), ), );
如果将上面例子中Text
widget所需要占用的空间变大,例如将字体变大,则Text
的父Container
按最大约束空间进行布局
Container( color: Colors.yellow, alignment: Alignment.centerLeft, child: Container( color: Colors.green, constraints: BoxConstraints( maxHeight: 300, maxWidth: 300, minHeight: 50, minWidth: 100 ), child: Text( "快狗打车", textDirection: TextDirection.ltr, fontSize: 300, style: TextStyle(color: Colors.black), ), ), );
以上就是Container
的基本用法