P13. Flutter 水平布局Row的使用
目录
Flutter 中的Row
控件就是水平控件,它可以让Row
里边的子元素进行水平排列。
Row
控件可以分为灵活排列和非灵活排列两种,这两种模式都需要熟练掌握,等经验丰富后可根据需求进行使用。
不灵活水平布局
从字面上就可以理解到,不灵活就是根据 Row 子元素的大小,进行布局。如果子元素不足,它会留有空隙,如果子元素超出,它会警告。
比如现在我们要制作三个按钮,并让三个按钮同时在一排。我们写下了如下代码,但你会发现效果并不理想。
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'ListView widget', home: Scaffold( appBar: AppBar( title: Text('水平方向布局'), ), body: Row( children: [ RaisedButton( onPressed: () {}, color: Colors.redAccent, child: Text('Red Button')), RaisedButton( onPressed: () {}, color: Colors.orangeAccent, child: Text('Orange Button'), ), RaisedButton( onPressed: () {}, color: Colors.pinkAccent, child: Text('Pink Button')) ], )), ); } }
效果如下:
这时候你会发现的页面已经有了三个按钮,但这三个按钮并没有充满一行,而是出现了空隙。这就是不灵活横向排列造成的。它根据子元素的大小来进行排列。如果我们想实现充满一行的效果,就要使用灵活水平布局了。
灵活水平布局
解决上面有空隙的问题,可以使用 Expanded
来进行解决,也就是我们说的灵活布局。我们在按钮的外边加入Expanded
就可以了,代码如下:
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'ListView widget', home: Scaffold( appBar: AppBar( title: Text('水平方向布局'), ), body: Row( children: [ Expanded( child: RaisedButton( onPressed: () {}, color: Colors.redAccent, child: Text('Red Button'))), Expanded( child: RaisedButton( onPressed: () {}, color: Colors.orangeAccent, child: Text('Orange Button'))), Expanded( child: RaisedButton( onPressed: () {}, color: Colors.pinkAccent, child: Text('Pink Button'))) ], )), ); } }
这时候就可以布满一行了,效果如下图:
灵活和不灵活的混用
如果这时候想让中间的按钮大,而两边的按钮保持真实大小,就可以不灵活和灵活模式进行混用,实现效果。代码和效果如下:
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'ListView widget', home: Scaffold( appBar: AppBar( title: Text('水平方向布局'), ), body: Row( children: [ RaisedButton( onPressed: () {}, color: Colors.redAccent, child: Text('Red Button')), Expanded( child: RaisedButton( onPressed: () {}, color: Colors.orangeAccent, child: Text('Orange Button'))), RaisedButton( onPressed: () {}, color: Colors.pinkAccent, child: Text('Pink Button')) ], )), ); } }
效果如下:
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » P13. Flutter 水平布局Row的使用
码云笔记 » P13. Flutter 水平布局Row的使用