移动开发中除了常用的flex 流式布局外,还有一种常用的布局,叫层叠布局。我就学习一下flutter的Stack 以及Positioned 定位。
先看一下效果:文本“大家好” 位于圆形图片之上。
一张原型图片上添加一行带背景的文字。使用Row Widget或者Column Widget是实现不了的,这时就需要使用Stack Widget,也就是层叠布局来实现了。
import 'package:flutter/material.dart';
// StackView 封装
Widget myStackView(BuildContext context) {
return Stack(
alignment: const Alignment(0.6, 0.6),
children: [
new CircleAvatar(
backgroundImage: new AssetImage('images/lake.png'),
radius: 100.0,
),
new Container(
decoration: new BoxDecoration(
color: Colors.black45,
),
child: new Text(
'大家好',
style: new TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
],
);
}
// 构建页面
class StackTest extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("StackTest"),
backgroundColor: Colors.orange,
),
body: Container(
color: Colors.blueGrey,
child:
myStackView(context),
),
);
}
}
代码解读:
myStackView() 类返回的组件就是Stack()。
CircleAvatar组件
CircleAvatar组件常用来作圆形头像,通过设置radius的值设置图片的弧度。
弧度:100,加载了一个本地的图片:lake.png
new CircleAvatar(
backgroundImage: new AssetImage('images/lake.png'),
radius: 100.0,
),
紧接着是一个Container 组件。
层叠布局的 alignment 属性(两个)
alignment: const Alignment(0.6, 0.6),
alignment 是控制层叠的位置的,建议在两个内容进行层叠时使用。它有两个值X轴距离和Y轴距离,值是从-1 到1 的,都是从上层容器的中心开始算起的。
Positioned属性 (两个以上)
如果超过两个组件的层叠,alignment属性就满足不了需求了,需要使用Positioned属性。所以这个组件也叫做层叠定位组件。
bottom: 距离层叠组件下边的距离
left:距离层叠组件左边的距离
top:距离层叠组件上边的距离
right:距离层叠组件右边的距离
width: 层叠定位组件的宽度
height: 层叠定位组件的高度
如下图:
图片上:一个“hello,world” 一个“大家好”
示例代码:
// StackView3 封装
Widget myStackView3(BuildContext context) {
return Stack(
alignment: const FractionalOffset(0.5, 0.95),
// alignment 对齐方式 0~1
children: <Widget>[
CircleAvatar(
// CircleAvatar 圆角
//https://www.zengxiaohui.com/skin/xiaohui/img/avatar.jpg
backgroundImage: NetworkImage('http://oss.suning.com/uedtool/png_bucket/20195/20190522095508918_灵栖ppt首页5.png'),
radius: 130.0, // 大小
),
Positioned(
top: 10.0,
left: 60.0,
child: Text('hello.world',
style: TextStyle(color: Colors.red,fontSize:24),
),
),
Positioned(
bottom: 10.0,
right: 100.0,
child: Text('大家好',
style: TextStyle(color: Colors.red,fontSize:24),
),
)
],
);
}
// 构建路由传参
class StackTest extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("StackTest"),
backgroundColor: Colors.orange,
),
body: Container(
color: Colors.blueGrey,
child:
myStackView3(context),
),
);
}
}
可以不断调整Positioned 的参数以满足我们的需求。这个类似 iOS 的frame 定位。相对于俯视图的坐标。
如果想用alignment 布局多个,我试了一下会重贴覆盖。所以多个只能改Positioned。
参看:
Flutter学习笔记十一——层叠布局Stack的使用
flutter层叠布局Stack,Positioned 定位