SizedBox.shrink()
可模擬 Null Widget,使得 mainAxisAlignment
的設定生效。
Version
Flutter 3.24.5
Flutter
- Android 與 iOS 都成功使用
SizedBox.shrink()
實現 Null Widget
SizedBox
import 'package:flutter/material.dart';
class Home extends StatefulWidget {
const Home({super.key});
State<Home> createState() => _Home();
}
class _Home extends State<Home> {
Widget build(BuildContext context) {
var appBar = AppBar(
title: const Text("SizedBox.shrink()"),
);
var row = Container(
color: Colors.grey[100],
padding: const EdgeInsets.all(16.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: const [
SizedBox.shrink(),
Text("Clickable Row"),
Icon(Icons.arrow_forward_ios),
],
),
);
var body = Center(
child: row,
);
return Scaffold(
appBar: appBar,
body: body,
);
}
}
Line 20
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: const [
SizedBox.shrink(),
Text("Clickable Row"),
Icon(Icons.arrow_forward_ios),
],
),
mainAxisAlignment: MainAxisAlignment.spaceBetween
:每個 widget 的間距相等,若只有三個 widget,則將置於左
、中
、右
SizedBox.shrink()
:模擬出 Null Widget,但沒有實際的寬高,這使得mainAxisAlignment: MainAxisAlignment.spaceBetween
能有作用,讓Text
看起來置中,Icon
看起來靠右
Conclusion
- Flutter 雖然沒有提供 Null Widget,但可使用
SizedBox.shrink()
實現