Stack这个widget主要是用来把几个widget进行叠加,Positioned则相当于父组件定位。
下来我们实现一个类似下面的雪花效果:
代码:
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData.light(),
home: Stack(
children: <Widget>[
SizedBox.expand( // 默认填满父元素
child: Container(
decoration: BoxDecoration(
color: Colors.lightBlue,
),
),
),
Positioned(
top: 250.0, // 距离父元素上方的距离
right: 20.0, // 距离父元素右方的距离
child: Container(
child: Icon(
Icons.ac_unit,
color: Colors.white,
size: 32.0,
),
decoration: BoxDecoration(
shape: BoxShape.circle,
gradient: RadialGradient(colors: [ // 添加渐变色
Color.fromRGBO(7, 102, 255, 1.0),
Color.fromRGBO(200, 200, 200, 0.5),
]),
),
)),
Positioned(
top: 70.0,
right: 10.0,
child: Icon(
Icons.ac_unit,
color: Colors.white,
size: 32.0,
),
),
Positioned(
top: 80.0,
right: 150.0,
child: Icon(
Icons.ac_unit,
color: Colors.white,
size: 32.0,
),
),
Positioned(
top: 90.0,
right: 40.0,
child: Icon(
Icons.ac_unit,
color: Colors.white,
size: 32.0,
),
),
Positioned(
top: 80.0,
right: -20.0,
child: Icon(
Icons.ac_unit,
color: Colors.white,
size: 32.0,
),
),
Positioned(
top: 200.0,
right: 300.0,
child: Icon(
Icons.ac_unit,
color: Colors.white,
size: 32.0,
),
),
Positioned(
top: 314.0,
right: 400.0,
child: Icon(
Icons.ac_unit,
color: Colors.white,
size: 32.0,
),
),
Positioned(
top: 400.0,
left: 40.0,
child: Icon(
Icons.ac_unit,
color: Colors.white,
size: 32.0,
),
),
Positioned(
top: 420.0,
right: 250.0,
child: Icon(
Icons.ac_unit,
color: Colors.white,
size: 32.0,
),
),
Positioned(
top: 500.0,
right: 230.0,
child: Icon(
Icons.ac_unit,
color: Colors.white,
size: 32.0,
),
),
Positioned(
top: 530.0,
right: 50.0,
child: Icon(
Icons.ac_unit,
color: Colors.white,
size: 32.0,
),
),
Positioned(
top: 570.0,
right: 260.0,
child: Icon(
Icons.ac_unit,
color: Colors.white,
size: 32.0,
),
),
Positioned(
top: 590.0,
right: 222.0,
child: Icon(
Icons.ac_unit,
color: Colors.white,
size: 32.0,
),
),
Positioned(
top: 620.0,
right: 290.0,
child: Icon(
Icons.ac_unit,
color: Colors.white,
size: 32.0,
),
),
Positioned(
top: 700.0,
right: 150.0,
child: Icon(
Icons.ac_unit,
color: Colors.white,
size: 32.0,
),
),
Positioned(
top: 800.0,
left: 40.0,
child: Icon(
Icons.ac_unit,
color: Colors.white,
size: 32.0,
),
),
],
),
);
}
}