[英]How to overlay a widget on an overlay widget
需要帮忙。 告诉我,我该如何实现这样的小部件,其中图片重叠在图片上,最后一个圆圈带有关于剩余小部件(头像)数量的数字? 据我了解,这是由 Stack 使用的,并添加了一个图像列表?
是的,答案是Stack
小部件结合Positioned
小部件:我做了演示来解释实现过程,CustomWidget 接受小部件列表并将它们转换为堆栈。
和代码:
class TestPage extends StatelessWidget {
TestPage({Key? key}) : super(key: key);
final List<String> demoImages = [
'https://www.nicesnippets.com/demo/following2.jpg',
'https://www.nicesnippets.com/demo/following1.jpg',
'https://www.nicesnippets.com/demo/following3.jpg',
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSgqRbJqrabB7q76uOOjEs2Oljk4CGBNpRdCNR4qhLnRWkIX0LKnLmedNS-ILmArB9cCaM&usqp=CAU'
];
@override
Widget build(BuildContext context) {
return Center(
child: PhotoWidget(photosLinks: demoImages),
);
}
}
class PhotoWidget extends StatelessWidget {
const PhotoWidget({Key? key, required this.photosLinks}) : super(key: key);
final List<String> photosLinks;
List<Widget> getPhotos() {
if (photosLinks.isEmpty) throw Exception('List is Empty');
var tmp = <Widget>[];
var maxNumber = (photosLinks.length <= 2) ? photosLinks.length : 2;
if (photosLinks.length > 2) {
tmp.add(Positioned(
left: 2 * 40,
child: CircleAvatar(
radius: 30,
child: Text(
'${photosLinks.length - 2}+',
style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
),
));
}
for (int i = 0; i < maxNumber; i++) {
tmp.add(Positioned(
left: (40 * (1 - i)).toDouble(),
child: CircleAvatar(
radius: 30,
backgroundImage: NetworkImage(photosLinks[i]),
),
));
}
return tmp;
}
@override
Widget build(BuildContext context) {
return SizedBox(
width: 150,
child: Stack(
children: getPhotos(),
),
);
}
}
您可以使用片段
SizedBox(
height: 64,
child: Stack(
children: List.generate(
itemCount > 3 ? 3 : itemCount,
(index) => Positioned(
left: itemCount == 1
? null
: 32.0 * ((itemCount > 3 ? 3 : itemCount) - index),,
child: index ==0 && itemCount > 3
? CircleAvatar(child: Text("+ ${itemCount - 2}"))
: CircleAvatar(
backgroundColor:
index.isEven ? Colors.red : Colors.purple,
),
),
),
),
),
在dartPad上运行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.