TextFormField
預設會占滿整個 Column,且本身也沒有提供 Margin 設定,但可透過 Padding
提供 TextFormField
所需的 Margin。
Version
Flutter 3.24
Flutter
- Android 與 iOS 都成功為
TextFormField
提供 margin 顯示
import 'package:flutter/material.dart';
class Home extends StatefulWidget {
const Home({super.key});
State<Home> createState() {
return _Home();
}
}
class _Home extends State<Home> {
final _textEditingController = TextEditingController();
var _greeting = '';
void initState() {
super.initState();
_textEditingController.text = 'Hello World';
_textEditingController.addListener(() {
setState(() {
_greeting = _textEditingController.text;
});
});
}
void dispose() {
_textEditingController.dispose();
super.dispose();
}
Widget build(BuildContext context) {
var appBar = AppBar(title: const Text('TextFormField'));
var textFormField = TextFormField(
controller: _textEditingController,
);
var text = Text(_greeting);
var body = Center(
child: Padding(
padding: const EdgeInsets.only(left: 16, right: 16),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
textFormField,
text,
],
),
),
);
return Scaffold(
appBar: appBar,
body: body,
);
}
}
Line 44
var body = Center(
child: Padding(
padding: const EdgeInsets.only(left: 16, right: 16),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
textFormField,
text,
],
),
),
);
- 在
Column
外側加上Padding
撐住左右 margin,column 縮小後,TextFormField
會自動改變寬度,但依然撐滿整個 column
Conclusion
- 雖然觀念上對
TextFormField
是 margin,但因為 Flutter 的風格是不斷向外堆 widget,因此對外層 widget 而言,其實是 padding,這也是爲什麼 Flutter 並沒有提供Margin
,而是提供Padding
的主因