將兩個 Widget 同時水平向左右兩側對齊是常見需求,可使用 Row
的mainAxisAlignment: MainAxisAlignment.spaceBetween
實現。
Version
Flutter 3.24
Flutter
- Android 與 iOS 都成功使用
MainAxisAlignment.spaceBetween
實現水平向左右兩側對齊
Row
import 'package:flutter/material.dart';
class Home extends StatelessWidget {
const Home({super.key});
Widget build(BuildContext context) {
var appBar = AppBar(
title: const Text('Row SpaceBetween'),
);
var column1 = Container(
color: Colors.blue,
width: 50,
height: 50,
);
var column2 = Container(
color: Colors.red,
width: 50,
height: 50,
);
var body = Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
column1,
column2,
],
),
);
return MaterialApp(
home: Scaffold(
appBar: appBar,
body: body,
),
);
}
}
Line 24
var body = Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
column1,
column2,
],
),
);
Row
:使 widget 水平排列MainAxisAlignment.spaceBetween
:水平向左右兩側對齊
Conclusion
spaceBetween
會平分 widget 剩餘的 width 放在兩個 widget 之間,因此相當於向左向右各自對齊- 與 CSS 的 Flex 的
justify-content: space-between;
意思相同