Flutter基础知识-布局篇

MaterialApp

  • MaterialApp封装了应用程序实现Material Design所需要的一些Widget

  • 一般作为顶层widget使用

  • 常用属性:

名称 类型 说明
home Widget 主页
title String 标题
color Color 颜色
theme ThemeData 主题
routes Map<String, WidgetBuilder> 路由
initialRoute String 初始化的时候加载的路由
onGenerateRoute RouteFactory 路由
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Flutter Demo'), ), body: HomeContent(), ), theme: ThemeData( primarySwatch: Colors.yellow ), ); } } class HomeContent extends StatelessWidget { @override Widget build(BuildContext context) { return new Center( child: new Text( '你好Flutter', textDirection: TextDirection.ltr, style: TextStyle ( fontSize: 40.0, color: Colors.yellow // color: Color.fromRGBO(244, 233, 121, 0.5) ), ) ); } }

Scaffold

  • ScaffoldMaterial Design布局结构的基本实现

  • 提供了用于显示drawersnackbar和底部sheetAPI

  • 常用属性:

名称 类型 说明
appBar AppBar 显示在界面顶部的一个AppBar
body Widget 当前界面所显示的主要内容Widget
drawer Drawer 左侧抽屉菜单控件
endDrawer Drawer 右侧抽屉菜单控件
bottomNavigationBar BottomNavigationBar 底部NavigationBar
floatingActionButton Widget 浮动按钮
floatingActionButtonLocation FloatingActionButtonLocation 浮动按钮位置
Scaffold( appBar: AppBar( title: Text('Flutter Demo'), ), floatingActionButton: Container( height: 60, width: 60, padding: EdgeInsets.all(6), margin: EdgeInsets.only(top: 10), decoration: BoxDecoration( borderRadius: BorderRadius.circular(30), color: Colors.white, ), child: FloatingActionButton( child: Icon(Icons.add), onPressed: (){ setState(() { this._currentIndex = 1; }); }, backgroundColor: this._currentIndex==1 ? Colors.blue : Colors.yellow, ), ), floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, body: this._pageList[this._currentIndex], bottomNavigationBar: BottomNavigationBar( currentIndex: this._currentIndex, // 对应的索引值引用 onTap: (int index) { setState(() { this._currentIndex = index; }); }, // iconSize: 36, // icon的大小 // fixedColor: Colors.red, // 选中的颜色 // type: BottomNavigationBarType.fixed, // 配置底部tabs可以有多个按钮 items: [ BottomNavigationBarItem( icon: Icon(Icons.home), title: Text('首页') ), BottomNavigationBarItem( icon: Icon(Icons.category), title: Text('分类') ), BottomNavigationBarItem( icon: Icon(Icons.settings), title: Text('设置') ), ], ), // 左侧侧边栏 drawer: Drawer( child: Column( children: <Widget>[ // DrawerHeader( // child: Text("你好Flutter"), // ), Row( children: <Widget>[ Expanded( // child: DrawerHeader( // child: Text("你好Flutter"), // decoration: BoxDecoration( // // color: Colors.yellow, // image: DecorationImage( // image: NetworkImage('https://www.itying.com/images/flutter/1.png'), // fit: BoxFit.cover, // ), // ), // ), child: UserAccountsDrawerHeader( accountName: Text("喵巨人"), accountEmail: Text("xxx@xxx.com"), currentAccountPicture: CircleAvatar( backgroundImage: NetworkImage('https://www.itying.com/images/flutter/1.png'), ), decoration: BoxDecoration( image: DecorationImage( image: NetworkImage('https://www.itying.com/images/flutter/2.png'), fit: BoxFit.cover ) ), otherAccountsPictures: <Widget>[ Image.network('https://www.itying.com/images/flutter/3.png'), Image.network('https://www.itying.com/images/flutter/4.png'), Image.network('https://www.itying.com/images/flutter/5.png'), ], ), ) ], ), ListTile( leading: CircleAvatar( child: Icon(Icons.home), ), title: Text("我的空间"), ), Divider(), ListTile( leading: CircleAvatar( child: Icon(Icons.people), ), title: Text("用户中心"), onTap: (){ // 隐藏侧边栏 Navigator.of(context).pop(); Navigator.pushNamed(context, '/user'); }, ), Divider(), ListTile( leading: CircleAvatar( child: Icon(Icons.settings), ), title: Text("设置中心"), ), ], ), ), // 右侧侧边栏 endDrawer: Drawer( child: Text("右侧侧边栏"), ), )

AppBar

  • AppBar常用属性:
名称 类型 说明
leading Widget 在标题前面显示的一个控件,在首页通常显示应用的logo;在其他界面通常显示为返回按钮
title Widget 标题,通常显示为当前界面的标题文字,可以放组件
actions List<Widget> 通常使用IconButton来表示,可以放按钮组
bottom PreferredSizeWidget 通常放tabBar,标题下面显示一个Tab导航栏
backgroundColor Color 导航背景颜色
iconTheme IconThemeData 图标样式
textTheme TextTheme 文字样式
centerTitle bool 标题是否居中显示
Scaffold( appBar: AppBar( title: Text("AppBarDemoPage"), // backgroundColor: Colors.red, centerTitle: true, // 左侧的图标 // leading: Icon(Icons.menu), // leading: IconButton( // icon: Icon(Icons.menu), // onPressed: (){ // print('menu'); // }, // ), // 右侧的图标 actions: <Widget>[ IconButton( icon: Icon(Icons.search), onPressed: (){ print('search'); }, ), IconButton( icon: Icon(Icons.settings), onPressed: (){ print('settings'); }, ), ], // bottom: Container(), ), body: Container(), )

Drawer

DrawerHeader

  • DrawerHeader常用属性
名称 类型 说明
decoration Decoration 设置顶部背景颜色
child Widget 子元素
padding EdgeInsetsGeometry 内边距
margin EdgeInsetsGeometry 外边距
DrawerHeader( child: Text("你好Flutter"), decoration: BoxDecoration( // color: Colors.yellow, image: DecorationImage( image: NetworkImage('https://www.itying.com/images/flutter/1.png'), fit: BoxFit.cover, ), ), ),

UserAccountsDrawerHeader

  • UserAccountsDrawerHeader常用属性
名称 类型 说明
decoration Decoration 设置顶部背景颜色
accountName Widget 账户名称
accountEmail Widget 账户邮箱
currentAccountPicture Widget 用户头像
otherAccountsPictures List<Widget> 用来设置当前账户其他账户头像
margin EdgeInsetsGeometry 外边距
UserAccountsDrawerHeader( accountName: Text("喵巨人"), accountEmail: Text("xxx@xxx.com"), currentAccountPicture: CircleAvatar( backgroundImage: NetworkImage('https://www.itying.com/images/flutter/1.png'), ), decoration: BoxDecoration( image: DecorationImage( image: NetworkImage('https://www.itying.com/images/flutter/2.png'), fit: BoxFit.cover ) ), otherAccountsPictures: <Widget>[ Image.network('https://www.itying.com/images/flutter/3.png'), Image.network('https://www.itying.com/images/flutter/4.png'), Image.network('https://www.itying.com/images/flutter/5.png'), ], )

BottomNavigationBar

  • BottomNavigationBar常用属性
名称 类型 说明
items List<BottomNavigationBarItem> 底部导航条按钮集合
iconSize double 图标大小
currentIndex int 默认选中第几个
onTap ValueChanged<int> 选中变化回调函数
fixedColor Color 选中的颜色
type BottomNavigationBarType fixedshifting
BottomNavigationBar( currentIndex: this._currentIndex, onTap: (int index) { setState(() { this._currentIndex = index; }); }, items: [ BottomNavigationBarItem( icon: Icon(Icons.home), title: Text('首页') ), BottomNavigationBarItem( icon: Icon(Icons.category), title: Text('分类') ), BottomNavigationBarItem( icon: Icon(Icons.settings), title: Text('设置') ), ], )

常用

Container

  • 常用属性:
名称 类型 说明
alignment AlignmentGeometry 对齐方式。Alignment.bottomLeft
decoration Decoration 设置背景色、边框、圆角等
margin EdgeInsetsGeometry 外边距。EdgeInsets.all(20.0)
padding EdgeInsetsGeometry 内边距
transform Matrix4 Container容易进行一些旋转之类的。transform: Matrix4.rotationZ(0.2)
width double 容器宽度
height double 容器高度
color Color 背景色
child Widget 容器子元素
Container( child: Text('各位同学大家好我是主讲老师大地,各位同学大家好我是主讲老师大地'), height: 300.0, width: 300.0, decoration: BoxDecoration( color: Colors.yellow, border: Border.all( color: Colors.blue, width: 2.0 ), borderRadius: BorderRadius.all( Radius.circular(10) ) ), padding: EdgeInsets.all(20), margin: EdgeInsets.fromLTRB(10, 30, 5, 0), alignment: Alignment.bottomLeft, )

Text

  • 常用属性:
名称 类型 说明
textAlign TextAlign 文本对齐方式(center居中,left左对齐,right右对齐,justfy两端对齐)
textDirection TextDirection 文本方向(ltr从左至右,rtl从右至左)
overflow TextOverflow 文字超出屏幕之后的处理方式(clip裁剪,fade渐隐,ellipsis省略号)
textScaleFactor double 字体显示倍率
maxLines int 文字显示最大行数
style TextStyle 字体的样式设置
  • TextStyle的参数
名称 类型 说明
decoration TextDecoration 文字装饰线(none没有线,lineThrough删除线,overline上划线,underline下划线)
decorationColor Color 文字装饰线颜色
decorationStyle TextDecorationStyle 文字装饰线风格([dashed,dotted]虚线,double两根线,solid一根实线,wavy波浪线)
wordSpacing double 单词间隙(如果是负值,会让单词变得更紧凑)
letterSpacing double 字母间隙(如果是负值,会让字母变得更紧凑)
fontStyle FontStyle 文字样式(italic斜体,normal正常体)
fontSize double 文字大小
color Color 文字颜色
fontWeight FontWeight 字体粗细(bold粗体,normal正常体)
Text( '显示的文字,显示的文字,显示的文字', textAlign: TextAlign.left, overflow: TextOverflow.ellipsis, maxLines: 2, textScaleFactor: 1.8, style: TextStyle( fontSize: 16.0, color: Colors.red, fontWeight: FontWeight.w800, fontStyle: FontStyle.italic, decoration: TextDecoration.lineThrough, decorationColor: Colors.white, decorationStyle: TextDecorationStyle.dashed, letterSpacing: 5.0 ), )

Button

  • 常用属性:
名称 类型 说明
onPressed VoidCallback,一般接收一个方法 必填参数,按下按钮时触发的回调,接收一个方法,传null表示按钮禁用,会显示禁用相关样式
child Widget 文本控件
color Color 按钮的颜色
textColor Color 文本颜色
disabledColor Color 按钮禁用时的颜色
disabledTextColor Color 按钮禁用时的文本颜色
splashColor Color 点击按钮时水波纹的颜色
highlightColor Color 点击(长按)按钮后按钮的颜色
elevation double 阴影的范围,值越大阴影范围越大
padding EdgeInsetsGeometry 内边距
shape ShapeBorder 设置按钮的形状

RaisedButton

  • 凸起的按钮,其实就是Material Design风格的Button
RaisedButton( child: Text("按钮"), color: Colors.blue, textColor: Colors.white, elevation: 5, onPressed: (){ print('按钮'); }, ) // RaisedButton.icon RaisedButton.icon( icon: Icon(Icons.search), label: Text("图标按钮"), color: Colors.blue, textColor: Colors.white, // onPressed如果置为null,表示禁用 // onPressed: null, onPressed: (){}, ) // 有高度的按钮 Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( width: 200, height: 50, child: RaisedButton( child: Text("有宽度和高度按钮"), color: Colors.blue, textColor: Colors.white, elevation: 10, onPressed: (){ print('有宽度和高度按钮'); }, ), ), ], ) // 自适应按钮 Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Expanded( // child: RaisedButton( // child: Text("自适应按钮"), // color: Colors.blue, // textColor: Colors.white, // elevation: 10, // onPressed: (){ // print('自适应按钮'); // }, // ), child: Container( height: 60, margin: EdgeInsets.all(10), child: RaisedButton( child: Text("自适应按钮"), color: Colors.blue, textColor: Colors.white, elevation: 10, onPressed: (){ print('自适应按钮'); }, ), ), ) ], ) // 圆角按钮 RaisedButton( child: Text("圆角按钮"), color: Colors.blue, textColor: Colors.white, elevation: 10, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), onPressed: (){ print('圆角按钮'); }, ) // 圆形按钮 Container( height: 80, child: RaisedButton( child: Text("圆形按钮"), color: Colors.blue, textColor: Colors.white, elevation: 10, // 水波纹 splashColor: Colors.grey, shape: CircleBorder( side: BorderSide( color: Colors.white, ) ), onPressed: (){ print('圆形按钮'); }, ), )

FlatButton

  • 扁平化的按钮

IconButton

  • 带图标按钮

OutlineButton

  • 带线框按钮
OutlineButton( child: Text("OutlineButton"), // color没有效果, textColor有效果 // color: Colors.red, textColor: Colors.yellow, onPressed: (){}, )

ButtonBar

  • 按钮组

FloatingActionButton

  • 浮动按钮

  • 常用属性:

名称 类型 说明
child Widget 子视图,一般为Icon,不推荐使用文字
tooltip String 被长按时显示,也是无障碍功能
backgroundColor Color 背景颜色
elevation double 未点击的时候的阴影
hignlightElevation double 点击时阴影值,默认12.0
onPressed VoidCallback 点击事件回调
shape ShapeBorder 定义形状等
mini bool 是否是mini类型默认false
Scaffold( appBar: AppBar( title: Text('Flutter Demo'), ), floatingActionButton: Container( height: 60, width: 60, padding: EdgeInsets.all(6), margin: EdgeInsets.only(top: 10), decoration: BoxDecoration( borderRadius: BorderRadius.circular(30), color: Colors.white, ), child: FloatingActionButton( child: Icon(Icons.add), onPressed: (){ setState(() { this._currentIndex = 1; }); }, backgroundColor: this._currentIndex==1 ? Colors.blue : Colors.yellow, ), ), floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, body: this._pageList[this._currentIndex], bottomNavigationBar: BottomNavigationBar( currentIndex: this._currentIndex, // 对应的索引值引用 onTap: (int index) { setState(() { this._currentIndex = index; }); }, // iconSize: 36, // icon的大小 // fixedColor: Colors.red, // 选中的颜色 // type: BottomNavigationBarType.fixed, // 配置底部tabs可以有多个按钮 items: [ BottomNavigationBarItem( icon: Icon(Icons.home), title: Text('首页') ), BottomNavigationBarItem( icon: Icon(Icons.category), title: Text('分类') ), BottomNavigationBarItem( icon: Icon(Icons.settings), title: Text('设置') ), ], ) )

Image

  • 常用的两个Image.assetImage.network

  • 圆角图形

// 外面包一个Container,给Container设置圆形 Container( width: 300.0, height: 300.0, decoration: BoxDecoration( color: Colors.yellow, borderRadius: BorderRadius.all( Radius.circular(150) ), // borderRadius: BorderRadius.circular(150), image: DecorationImage( image: NetworkImage('https://www.itying.com/images/201905/thumb_img/1101_thumb_G_1557845381862.jpg'), fit: BoxFit.cover ) ), )
// 使用ClipOval ClipOval( child: Image.network( 'http://www.ionic.wang/statics/index/images/ionic4.png', width: 100, height: 100, fit: BoxFit.cover ), )

网络图片

  • Image.network常用属性:
名称 类型 说明
alignment Alignment 图片的对齐方式
color Color 设置图片的背景颜色,通常和colorBlendMode配合一起使用,这样可以是图片颜色和背景色混合
fit BoxFit 控制图片的拉伸和挤压,是根据父容器来的。常用fillcontaincoverfitWidthfitHeight
repeat ImageRepeat repeatrepeatXrepeatY
width double 宽度,一般结合ClipOval才能看到效果
height double 高度,一般结合ClipOval才能看到效果
Image.network( 'http://www.ionic.wang/statics/index/images/ionic4.png', // alignment: Alignment.bottomRight, // color: Colors.blue, fit: BoxFit.cover, // repeat: ImageRepeat.repeat, )

本地图片

  • 将图片放在images/目录下的对应目录中

  • 修改pubspec.yaml文件,声明一下添加的图片文件

flutter: # ... assets: - images/a.jpg - images/2.0x/a.jpg - images/3.0x/a.jpg
  • 在代码中使用
Image.asset("images/a.jpg", fit: BoxFit.cover)

页面布局

Paddiing

  • 常用属性:
名称 类型 说明
padding EdgeInsetsGeometry 内边距
child Widget 容器子元素
Padding( padding: EdgeInsets.fromLTRB(10, 10, 0, 0), child: Image.network('https://www.itying.com/images/flutter/1.png', fit: BoxFit.cover,), )

Row

  • 水平布局组件

  • 常用属性:

名称 类型 说明
mainAxisAlignment MainAxisAlignment 主轴的排序方式
crossAxisAlignment CrossAxisAlignment 次轴的排序方式
children List<Widget> 组件子元素
Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ IconContainer(Icons.search, color: Colors.blue,), IconContainer(Icons.home, color: Colors.orange,), IconContainer(Icons.select_all, color: Colors.red,), ], )

Column

  • 垂直布局组件

  • 常用属性:

名称 类型 说明
mainAxisAlignment MainAxisAlignment 主轴的排序方式
crossAxisAlignment CrossAxisAlignment 次轴的排序方式
children List<Widget> 组件子元素
Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ IconContainer(Icons.search, color: Colors.blue,), IconContainer(Icons.home, color: Colors.orange,), IconContainer(Icons.select_all, color: Colors.red,), ], )

Center

  • 居中布局
Center( child: Text('hello') )

Align

  • 我们常常在Container里,需要显示的内容在左上角,左下角,右上角,右下角等
Container( color: Colors.blue, width: 300, height: 200, child: Align( alignment: Alignment.bottomRight, child:Text( "Hello Align ", style:TextStyle( fontSize: 20, color: Colors.white ) ), ) )

Expanded

  • 类似于Flex布局

  • Expanded可以用在RowColumnFlex布局中

  • 如果轴向不确定,使用Flex,通过修改direction的值设定轴向

  • 如果轴向已确定,使用RowColumn,布局更简洁,更有语义化

  • 常用属性:

名称 类型 说明
flex int 元素站整个父Row/Column的比例
child Widget 子元素
// Row Row( children: <Widget>[ Expanded( flex: 1, child: IconContainer(Icons.search, color: Colors.blue,), ), Expanded( flex: 2, child: IconContainer(Icons.home, color: Colors.orange,), ), IconContainer(Icons.search, color: Colors.blue,), ], ) // Flex Flex( direction: Axis.horizontal, children: <Widget>[ Container( width: 30, height: 100, color: Colors.blue, ), Expanded( flex: 1, child: Container( height: 100.0, color: Colors.red, ), ), Expanded( flex: 1, child: Container( height: 100.0, color: Colors.green, ), ), ], )

Stack

  • 绝对定位

  • 层叠组件,表示的意思

  • 对于positioned的子节点,它们的位置会根据所设置的topbottomright以及left属性来确定,这几个值都是相对于Stack的左上角

  • 对于non-positioned的子节点,它们会根据Stackaligment来设置位置

  • 对于绘制child的顺序,则是第一个child被绘制在最底端,后面的依次在前一个child的上面。如果想调整显示的顺序,则可以通过摆放child的顺序来进行

  • 常用属性:

名称 类型 说明
alignment AlignmentGeometry 配置所有子元素的显示位置
children List<Widget> 子组件
Stack( alignment: Alignment.bottomLeft, children: <Widget>[ Container( width: 400.0, height: 400.0, color: Colors.red, ), Text('我是一个文本', style: TextStyle( fontSize: 40, color: Colors.white ),), ], )
  • Stack组件中结合Align组件可以控制每个子元素的显示位置
Stack( // alignment: Alignment.center, children: <Widget>[ Align( alignment: Alignment(1, -0.2), child: Icon(Icons.home, size: 40, color: Colors.white,), ), Align( alignment: Alignment.center, child: Icon(Icons.search, size: 30, color: Colors.white,), ), Align( alignment: Alignment.bottomRight, child: Icon(Icons.send, size: 60, color: Colors.orange,), ), ], )
  • Stack组件中结合Positioned组件也可以控制每个子元素的显示位置
Stack( // alignment: Alignment.center, children: <Widget>[ Positioned( left: 10, child: Icon(Icons.home, size: 40, color: Colors.white,), ), Positioned( bottom: 0, left: 100, child: Icon(Icons.search, size: 30, color: Colors.white,), ), Positioned( right: 0, top: 300, child: Icon(Icons.send, size: 60, color: Colors.orange,), ), ], )

IndexedStack

  • 继承自Stack,它的作用是显示第indexchild,其他child都是不可见的

  • IndexedStack的尺寸永远是跟最大的子节点尺寸一致

Container( color: Colors.yellow, child: IndexedStack( // 这里设置的是1 就是显示含文本的Container的节点 index: 1, alignment: const Alignment(0.6, 0.6), children: [ CircleAvatar( backgroundImage: AssetImage('images/pic.jpg'), radius: 100.0, ), Container( decoration: BoxDecoration( color: Colors.black45, ), child: Text( 'Mia B', style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.white, ), ), ), ], ), )

Wrap

  • Wrap可以实现流布局

  • mainAxis上空间不足时,则向crossAxis上去扩展显示

  • 常用属性:

名称 类型 说明
direction Axis 主轴的方向,默认水平
alignment WrapAlignment 主轴的对其方式
spacing double 主轴方向上的间距
textDirection TextDirection 文本方向
verticalDirection VerticalDirection 定义了children摆放顺序,默认是down
runAlignment WrapAlignment run的对齐方式。run可以理解为新的行或者列,如果是水平方向布局的话,run可以理解为新的一行
runSpacing double run的间距
Wrap( spacing: 10, runSpacing: 10, direction: Axis.vertical, // alignment: WrapAlignment.spaceAround, // runAlignment: WrapAlignment.center, children: <Widget>[ MyButton('第1季'), MyButton('第2季第2季'), MyButton('第3季'), MyButton('第4季第4季第4季'), MyButton('第5季'), MyButton('第6季'), MyButton('第7季'), ], )

列表

ListView

  • 常用属性:
名称 类型 说明
scrollDirection Axis 水平列表horizontal、垂直列表vertical
padding EdgeInsetsGeometry 内边距
resolve bool 组件反向排序
children List<Widget> 元素列表
class HomeContent extends StatelessWidget { // 自定义方法 // List<Widget> _getData() { // var tempList = listData.map((value) { // return ListTile( // leading: Image.network(value['imageUrl']), // title: Text(value['title']), // subtitle: Text(value['author']), // ); // }); // return tempList.toList(); // } List<Widget> _getData() { var tempList = listData.map((value) { return ListTile( leading: Image.network(value['imageUrl']), title: Text(value['title']), subtitle: Text(value['author']), ); }); return tempList.toList(); } @override Widget build(BuildContext context) { return ListView( children: this._getData(), ); } }
// 使用ListView.builder class HomeContent extends StatelessWidget { List list = new List(); HomeContent() { for (var i = 0; i < 20; i++) { this.list.add('我是第$i条'); } } @override Widget build(BuildContext context) { return ListView.builder( itemCount: this.list.length, itemBuilder: (context, index) { return ListTile( title: Text(this.list[index]), ); }, ); } }

GridView

  • 网格列表组件

  • 常用属性:

名称 类型 说明
scrollDirection Axis 滚动方法
padding EdgeInsetsGeometry 内边距
resolve bool 反向排序
crossAxisSpacing double 水平子Widget之间间距
mainAxisSpacing double 垂直子Widget之间间距
crossAxisCount int 一行的Widget数量
childAspectRatio double Widget宽高比例
children List<Widget> 元素列表
// GridView.count class HomeContent extends StatelessWidget { List<Widget> _getListData() { var tempList = listData.map((value) { return Container( child: Column( children: <Widget>[ Image.network(value['imageUrl']), SizedBox(height: 12), Text( value['title'], textAlign: TextAlign.center, style: TextStyle(fontSize: 20.0), ) ], ), decoration: BoxDecoration( border: Border.all( color: Color.fromRGBO(233, 233, 233, 0.9), width: 1 ) ), // height: 400.0, // 设置高度没有反应 ); }); return tempList.toList(); } @override Widget build(BuildContext context) { return GridView.count( crossAxisSpacing: 20.0, // 水平子 Widget 之间间距 mainAxisSpacing: 20.0, // 垂直子 Widget 之间间距 padding: EdgeInsets.all(10), crossAxisCount: 2, // 一行的 Widget 数量 childAspectRatio: 0.7, // 宽度和高度的比例 children: this._getListData(), ); } }
// GridView.builder class HomeContent extends StatelessWidget { Widget _getListData(context, index) { return Container( child: Column( children: <Widget>[ Image.network(listData[index]['imageUrl']), SizedBox(height: 12), Text( listData[index]['title'], textAlign: TextAlign.center, style: TextStyle(fontSize: 20.0), ) ], ), decoration: BoxDecoration( border: Border.all( color: Color.fromRGBO(233, 233, 233, 0.9), width: 1 ) ), // height: 400.0, // 设置高度没有反应 ); } @override Widget build(BuildContext context) { return GridView.builder( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, crossAxisSpacing: 10.0, mainAxisSpacing: 10.0 ), itemCount: listData.length, itemBuilder: this._getListData, ); } }

AspectRatio

  • 根据设置调整子元素child的宽高比

  • 常用属性:

名称 类型 说明
aspectRatio double 宽高比,最终可能不会根据这个值去布局,具体则要看综合因素,外层是否允许按照这种比率进行布局,这只是一个参考值
child Widget 子组件
Container( width: 200.0, child: AspectRatio( aspectRatio: 2.0/1.0, child: Container( color: Colors.red, ), ), )

Card

  • Card是卡片组件块,内容可以由大多数类型的Widget构成

  • Card具有圆角和阴影,这让它看起来有立体感

  • 常用属性:

名称 类型 说明
margin EdgeInsetsGeometry 外边距
child Widget 子组件
Shape ShapeBorder 阴影效果,默认的阴影效果为圆角的长方形边
Card( margin: EdgeInsets.all(10), child: Column( children: <Widget>[ AspectRatio( aspectRatio: 16/9, child: Image.network('https://www.itying.com/images/flutter/1.png', fit: BoxFit.cover,), ), ListTile( // leading: ClipOval( // child: Image.network('https://www.itying.com/images/flutter/1.png', fit: BoxFit.cover, width: 60, height: 60,), // ), leading: CircleAvatar( backgroundImage: NetworkImage('https://www.itying.com/images/flutter/2.png'), ), title: Text("xxx"), subtitle: Text("xxxx"), ) ], ), ),

表单

TextField

  • 单行文本框、多行文本框、密码框等

  • 常用属性:

名称 类型 说明
maxLines int 设置此参数可以把文本框改为多行文本框
onChanged ValueChanged<String> 文本框改变的时候触发的事件
decoration InputDecoration hintTextborderlabelTextlabelStyle
obscureText bool 把文本框框改为密码框
controller TextEditingController 结合TextEditingController()可以配置表单默认显示的内容
TextField( // 设置maxLines后就是多行文本框 // maxLines: 4, // 密码框 // obscureText: true, decoration: InputDecoration( hintText: "请输入搜索的内容", // 边框 border: OutlineInputBorder(), icon: Icon(Icons.people), ), ) TextField( decoration: InputDecoration( border: OutlineInputBorder(), labelText: "用户名" ), ),
class _TextFieldPageState extends State<TextFieldPage> { // 初始化的时候给表单赋值 var _username = new TextEditingController(); var _password; @override void initState() { super.initState(); _username.text = "初始值123"; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("表单演示页面"), ), body: Padding( padding: EdgeInsets.all(20), child: Column( children: <Widget>[ TextField( decoration: InputDecoration( hintText: "请输入用户名", ), controller: _username, onChanged: (value){ // 这么写貌似是有问题 // _username.text = value; }, ), SizedBox(height: 10,), TextField( obscureText: true, decoration: InputDecoration( hintText: "密码", ), onChanged: (value){ _password = value; }, ), SizedBox(height: 10,), Container( // 自适应container width: double.infinity, child: RaisedButton( child: Text("登录"), color: Colors.blue, textColor: Colors.white, onPressed: (){ print(this._username.text); print(this._password); }, ), ), ], ), ), ); } }

CheckBox、CheckboxListTile

  • Checkbox常用属性:
名称 类型 说明
value bool true或者false
onChanged ValueChanged<bool> 改变的时候触发的事件
activeColor Color 选中的颜色、背景颜色
checkColor Color 选中的颜色、Checkbox里面对号的颜色
Checkbox( value: this.flag, onChanged: (v){ setState(() { this.flag = v; }); }, activeColor: Colors.red, )
  • CheckboxListTile常用属性:
名称 类型 说明
value bool true或者false
onChanged ValueChanged<bool> 改变的时候触发的事件
activeColor Color 选中的颜色、背景颜色
title Widget 标题
subtitle Widget 二级标题
secondary Widget 配置图标或者图片
selected bool 选中的时候文字颜色是否跟着改变
CheckboxListTile( value: this.flag, onChanged: (v){ setState(() { this.flag = v; }); }, title: Text("标题"), subtitle: Text("二级标题"), secondary: Icon(Icons.help), selected: this.flag, )

Radio、RadioListTile

  • Radio常用属性:
名称 类型 说明
value T 单选的值
onChanged ValueChanged<T> 改变的时候触发的事件
activeColor Color 选中的颜色、背景颜色
groupValue T 选择组的值
Row( children: <Widget>[ Text("男"), Radio( value: 1, onChanged: (v){ setState(() { this.sex = v; }); }, groupValue: this.sex, ), SizedBox(width: 20,), Text("女"), Radio( value: 2, onChanged: (v){ setState(() { this.sex = v; }); }, groupValue: this.sex, ), ], ),
  • RadioListTile常用属性:
名称 类型 说明
value T 单选的值
onChanged ValueChanged<T> 改变的时候触发的事件
activeColor Color 选中的颜色、背景颜色
title Widget 标题
subtitle Widget 二级标题
secondary Widget 配置图标或者图片
groupValue T 选择组的值
RadioListTile( value: 1, onChanged: (v){ setState(() { this.sex = v; }); }, groupValue: this.sex, title: Text("标题"), subtitle: Text("这是二级标题"), secondary: Icon(Icons.help), // 选中状态 selected: this.sex==1, ), RadioListTile( value: 2, onChanged: (v){ setState(() { this.sex = v; }); }, groupValue: this.sex, title: Text("标题"), subtitle: Text("这是二级标题"), secondary: Image.network('https://www.itying.com/images/flutter/6.png'), selected: this.sex==2, )

Switch、SwitchListTile

  • Switch常用属性:
名称 类型 说明
value bool 单选的值
onChanged ValueChanged<bool> 改变的时候触发的事件
activeColor Color 选中的颜色、背景颜色
Switch( value: this.flag, onChanged: (v){ setState(() { this.flag = v; }); }, )

相关文章


创作不易,若本文对你有帮助,欢迎打赏支持作者!

 分享给好友: