1. Stack 组件
Stack 表示堆的意思,用此组件修饰的子组件会“堆”在一起。
常见属性:
1. alignment 对齐方式;
2. children 子组件;
代码示例:
import 'package:flutter/material.dart';void main(){runApp(MyApp());
}// 抽离成一个单独的组件
class MyApp extends StatelessWidget{@overrideWidget build(BuildContext context) {return MaterialApp(home: Scaffold(// 导航条appBar:AppBar(title:Text('Flutter App')),// 主体body:HomeContent(),),// 主题theme: ThemeData(primarySwatch:Colors.yellow),);}
}// 利用Stack的alignment实现定位
class HomeContent extends StatelessWidget{@overrideWidget build(BuildContext context) {// Stack会将里面的子组件堆叠到一起return Center(child:Stack(// 直接指定方位,共9个// alignment: Alignment.center,// 用数值来表示方位,x和y的值位于-1到1之间// 0,0表示居中显示alignment: Alignment(1,0),children: [Container(height:400,width:300,color:Colors.red),Text("这是一个文本",style:TextStyle(fontSize: 20.0,color:Colors.green)), ],));}
}
效果图如下:
2. Stack与Align实现定位
Align组件专用于修饰子组件的对齐方式。
常见属性:
1. alignment 对齐方式;
2. children 子组件;
代码示例:
import 'package:flutter/material.dart';void main(){runApp(MyApp());
}// 抽离成一个单独的组件
class MyApp extends StatelessWidget{@overrideWidget build(BuildContext context) {return MaterialApp(home: Scaffold(// 导航条appBar:AppBar(title:Text('Flutter App')),// 主体body:HomeContent(),),// 主题theme: ThemeData(primarySwatch:Colors.yellow),);}
}// 利用Stack与Align实现多个子组件的定位
class HomeContent extends StatelessWidget{@overrideWidget build(BuildContext context) {return Center(child:Container(height:400,width:300,color:Colors.red,child:Stack(children: [Align(alignment:Alignment.topLeft,child:Icon(Icons.home,size:40,color:Colors.blue)),Align(// 对齐方式也可以使用数值表示alignment: Alignment(0,-1),child:Icon(Icons.search,size:40,color:Colors.white)),Align(alignment: Alignment.topRight,child:Icon(Icons.inbox,size:40,color:Colors.black))],)));}
}
效果图如下:
3. Stack与Postioned实现定位
Positioned组件用于对子组件进行定位。
常见属性:
1. top 子元素距离顶部的距离;
2. bottom 子元素距离底部的距离;
3. left 子元素距离左侧距离;
4. right 子元素距离右侧距离;
5. child 子组件;
代码示例:
import 'package:flutter/material.dart';void main(){runApp(MyApp());
}// 抽离成一个单独的组件
class MyApp extends StatelessWidget{@overrideWidget build(BuildContext context) {return MaterialApp(home: Scaffold(// 导航条appBar:AppBar(title:Text('Flutter App')),// 主体body:HomeContent(),),// 主题theme: ThemeData(primarySwatch:Colors.yellow),);}
}// 利用Stack与Positioned实现多个子组件的定位
class HomeContent extends StatelessWidget{@overrideWidget build(BuildContext context) {return Center(child:Container(height:400,width:300,color:Colors.red,child:Stack(children: [// 位置组件可以定位4个方向的// 一般用两个方位即可Positioned(bottom:0,left:0,child:Icon(Icons.home,size:40,color:Colors.blue)),Positioned(bottom:0,left:130,child:Icon(Icons.search,size:40,color:Colors.white)),Positioned(bottom:0,right:0,child:Icon(Icons.inbox,size:40,color:Colors.black))],)));}
}
效果图如下: