Flutter中使用Stack
和Positioned
这两个组件来配合实现绝对定位。Stack
允许子组件堆叠,而Positioned
用于根据Stack
的四个角来确定子组件的位置。
一.属性列表
Stack
Stack({this.alignment = AlignmentDirectional.topStart, this.textDirection,this.fit = StackFit.loose,this.overflow = Overflow.clip,List<Widget> children = const <Widget>[],
})
alignment
:此参数决定如何去对齐没有定位(没有使用Positioned
)或部分定位的子组件。textDirection
:与Row
、Wrap
的textDirection的
功能一样,都用于确定alignment
对齐的参考系,即:textDirection
的值为TextDirection.ltr
,则alignment
的start
代表左,end
代表右,即从左往右
的顺序;textDirection
的值为TextDirection.rtl
,则alignment的start
代表右,end
代表左,即从右往左
的顺序。fit
:此参数用于确定没有定位的子组件如何去适应Stack
的大小。overflow
:此属性决定如何显示超出Stack
显示空间的子组件。
Positioned
const Positioned({Key? key,this.left, //子元素距离左侧的距离this.top, //子元素距离顶部的距离this.right, //子元素距离右侧的距离this.bottom, //子元素距离底部的距离this.width,this.height,required Widget child,
})
二.示例
上图的源代码如下(仅截取使用到Stack、Positioned部分)
Container(child: Stack(children: [Container(height: 160.0,width: 290.0,margin: const EdgeInsets.only(top: 75,left: 20),decoration: const BoxDecoration(color: Colors.white,boxShadow: [BoxShadow(color: Colors.grey,offset: Offset(0.0, 0.1),//阴影xy轴偏移量blurRadius: 10,//阴影模糊程度spreadRadius: 0.5//阴影扩散测程度),],),),Container(height: 160.0,width: 330.0,margin: const EdgeInsets.only(top: 60),decoration: const BoxDecoration(color: Colors.pinkAccent,boxShadow: [BoxShadow(color: Colors.grey,offset: Offset(0.0, 0.1),//阴影xy轴偏移量blurRadius: 10,//阴影模糊程度spreadRadius: 0.5//阴影扩散测程度),],),),Positioned(bottom: 20,child: Image.asset("images/Ding.jpeg",width: 110,height: 250,),),const Positioned(top: 65,left: 130,child:Text("Seven",style: TextStyle(color: Colors.white,fontSize: 30,),) ,)],)),