Flutter中如何缩小纵向排列的Radio按钮之间的间距?
调整Radio按钮间距的解决方案
当前UI效果:
问题:无法让A.D.和B.C.的Radio按钮靠得更近,它们当前与TextField的顶部、底部对齐。尝试调整MainAxisAlignment、CrossAxisAlignment,添加SizedBox后仍无改善。
相关代码:
Row( children: [ Expanded( flex: 2, child: Padding( padding: const EdgeInsets.all(8.0), child: TextField( focusNode: inputNode, autofocus: true, keyboardType: const TextInputType.numberWithOptions(), controller: yearController, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: "Enter the Year", ), ), ), ), Expanded( flex: 1, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Radio<Era>( value: Era.ad, groupValue: _era, onChanged: (Era? value) { setState(() { _era = value; }); }, ), const Text( 'A.D.', style: TextStyle(fontSize: 10.0), ), ], ), Row( children: [ Radio<Era>( value: Era.bc, groupValue: _era, onChanged: (Era? value) { setState(() { _era = value; }); }, ), const Text( 'B.C.', style: TextStyle(fontSize: 10.0), ), ], ), ]) ]),
解决方法
问题根源在于右侧的Column因外层Expanded占据了TextField的全部高度,导致两个Radio行被上下撑开。同时Radio组件默认带有内边距,也会放大间距。可以通过以下两步调整:
- 让Column内的Radio行居中聚集
给右侧的Column添加mainAxisAlignment: MainAxisAlignment.center,让两个Radio行在垂直方向居中,避免上下贴边:
Expanded( flex: 1, child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, // 添加这一行 children: [ // ... 原有Radio行代码 ] ) ),
- 缩小Radio组件的默认间距
给每个Radio添加visualDensity: VisualDensity.compact,减少组件自身的内边距,让Radio和文字更紧凑:
Radio<Era>( value: Era.ad, groupValue: _era, onChanged: (Era? value) { setState(() { _era = value; }); }, visualDensity: VisualDensity.compact, // 添加这一行 ),
如果还需要进一步缩小两个Radio行之间的间距,可以在两个Row之间添加一个高度更小的SizedBox,比如:
Row(/* A.D. Radio代码 */), const SizedBox(height: 4), // 自定义间距 Row(/* B.C. Radio代码 */),
内容的提问来源于stack exchange,提问作者TM Lynch
相关产品推荐
相关产品推荐

