状況
日付入力用のテキストフォームとカレンダーアイコンを横並びに設置しようとすると、
ビルド時にエラーが出たので、その解決方法を共有。
修正前のソース
Row(
children: [
TextFormField(
keyboardType: TextInputType.number,
controller: dateController,
decoration: const InputDecoration(
labelText: '日付',
border: OutlineInputBorder(),
),
onSaved: (String value) {
setState(() {
dateController.text = value;
});
},
),
),
IconButton(
icon: Icon(calendar),
onPressed: () async {
// アイコン押下時のイベント
}),
],
),
エラー内容
EXCEPTION CAUGHT BY RENDERING LIBRARY
The following assertion was thrown during performLayout():
An InputDecorator, which is typically created by a TextField, cannot have an unbounded width.
This happens when the parent widget does not provide a finite width constraint. For example, if the
InputDecorator is contained by a Row, then its width must be constrained. An Expanded widget or a
SizedBox can be used to constrain the width of the InputDecorator or the TextField that contains it.
TextFormFieldには固有の幅がなく、
親要素の全幅にTextFormFieldのサイズを設定しようとしてエラーが起こっている。
解決方法
Flexible配下に置くことでよしなに幅を調節してくれる。
Flexible(
//この中にTextFormFieldを設置
)
修正後のソース
Row(
children: [
Flexible( // ←追加
child: TextFormField(
keyboardType: TextInputType.number,
controller: dateController,
decoration: const InputDecoration(
labelText: '日付',
border: OutlineInputBorder(),
),
onSaved: (String value) {
setState(() {
dateController.text = value;
});
},
),
),
IconButton(
icon: Icon(calendar),
onPressed: () async {
// アイコン押下時のイベント
}),
],
),