如果你想灵活控制Flex容器(Row, Column)中子组件中的间隔,可以考虑使用Spacer。下面以Row为例子,来为它的子组件添加间距。
use Spacer
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: Scaffold(
body: Center(
child: Row(
children: <Widget>[
FlutterLogo(colors: Colors.blue),
Spacer(flex: 2),
FlutterLogo(colors: Colors.pink),
Spacer(flex: 4),
FlutterLogo(colors: Colors.green),
Spacer(),
FlutterLogo(colors: Colors.pink),
],
),
),
),
);
}
}
the result:
use Row mainAxisAlignment
spacebetween
spaceAround
spaceEvenly
Summary
Row(
children: <Widget>[
FlutterLogo(colors: Colors.blue),
Spacer(),
FlutterLogo(colors: Colors.pink),
Spacer(),
FlutterLogo(colors: Colors.green),
Spacer(),
FlutterLogo(colors: Colors.pink),
],
)
与mainAxisAlignment=spacebetween的效果一样。但是使用Spacer可以提供更高的灵活性去设置组件之间的间距。Spacer的源码其实就是一个空的Expanded组件。
class Spacer extends StatelessWidget {
const Spacer({Key key, this.flex = 1})
: assert(flex != null),
assert(flex > 0),
super(key: key);
final int flex;
@override
Widget build(BuildContext context) {
return Expanded(
flex: flex,
child: const SizedBox.shrink(),
);
}
}