在日常的开发中,我们可能会遇到以下的需求:
多个元素重叠在一起。
这种需求我们可以使用Stack
组件来实现。这篇博客分享Stack
的组件知识,希望对看文章的小伙伴有所帮助。
示例代码
Stack(
alignment: Alignment.center,
children: <Widget>[
Container(
width: 400,
height: 400,
color: Colors.redAccent,
),
Container(
width: 300,
height: 300,
color: Colors.yellowAccent,
),
Container(
width: 200,
height: 200,
color: Colors.blueAccent,
),
],
)
使用效果如下:
image.png
完整的代码
以下的代码,可以直接复制到编译器去运行,方便小伙伴查看运行结果或者直接使用:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Stack Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Stack(
alignment: Alignment.center,
children: <Widget>[
Container(
width: 400,
height: 400,
color: Colors.redAccent,
),
Container(
width: 300,
height: 300,
color: Colors.yellowAccent,
),
Container(
width: 200,
height: 200,
color: Colors.blueAccent,
),
],
),
);
}
}
源码
Stack({
Key? key,
this.alignment = AlignmentDirectional.topStart,
this.textDirection,
this.fit = StackFit.loose,
@Deprecated(
'Use clipBehavior instead. See the migration guide in flutter.dev/go/clip-behavior. '
'This feature was deprecated after v1.22.0-12.0.pre.',
)
this.overflow = Overflow.clip,
this.clipBehavior = Clip.hardEdge,
List<Widget> children = const <Widget>[],
}) : assert(clipBehavior != null),
super(key: key, children: children);
属性说明
这里针对源码做出相应的属性说明,熟悉控件的属性方便大家的使用:
属性名称 | 属性说明 |
---|---|
alignment | 子组件摆放的位置 |
fit | 子组件的填充方式 |
clipBehavior | 剪辑小部件的内容 |
children | 布局里面堆叠在一起的子组件 |
网友评论