美文网首页
flutter 中Stack使用小技巧

flutter 中Stack使用小技巧

作者: coder小鹏 | 来源:发表于2024-06-30 17:18 被阅读0次

需求背景

在原生开发的时候,往往会遇到子视图超出父视图的情景,拿ios 举例,要实习这种效果,只需要设置子视图相对父视图的距离为负数,就可以实现上述效果.那么问题来了,在flutter中该如何实现呢,我们知道Stack是可以实现堆叠效果的,然后按照原生的思路,编写代码如下:

Stack(
             children: [
               Container(
                 color: Colors.blue,
                 child: Image.asset(
                   'lib/asset/image/icon_home_plan_message.png',
                   width: 36,
                   height: 36,
                   fit: BoxFit.cover,
                 )
               ),
               Positioned(
                   top: -5,
                   right: -5,
                   child: ClipRRect(
                     borderRadius: BorderRadius.circular(5),
                     child: Container(
                       color: Colors.red,
                       width: 10,
                       height: 10,
                     )
                   )
               ),
             ],
           )

运行后,效果如下:
[图片上传失败...(image-d45244-1719825498463)]
观察发现,虽然我们这种了小圆点的top和right为负数,但是并没有如我们想象的一样,小圆点被裁剪掉了,查看Stack源码后,发现Stack有clipBehavior属性,默认是Clip.hardEdge,会将其裁剪,将其改为Clip.none即可,具体代码如下

Stack(
             clipBehavior:Clip.none,
             children: [
               Container(
                 color: Colors.blue,
                 child: Image.asset(
                   'lib/asset/image/icon_home_plan_message.png',
                   width: 36,
                   height: 36,
                   fit: BoxFit.cover,
                 )
               ),
               Positioned(
                   top: -5,
                   right: -5,
                   child: ClipRRect(
                     borderRadius: BorderRadius.circular(5),
                     child: Container(
                       color: Colors.red,
                       width: 10,
                       height: 10,
                     )
                   )
               ),
             ],
           )

运行后的效果如下
[图片上传失败...(image-ac8742-1719825498463)]
最终实现了我们想要的效果

相关文章

网友评论

      本文标题:flutter 中Stack使用小技巧

      本文链接:https://www.haomeiwen.com/subject/ydypcjtx.html