Flutter:如何创建带图片和文字的CheckboxListTile
解决CheckboxListTile横向排列图片、文字和复选框的问题
空白屏的常见原因
- 图片资源配置错误:确认
images/image_1.png已放入项目对应目录,且在pubspec.yaml中正确声明assets:flutter: assets: - images/ - 未使用StatefulWidget:
_isChecked状态需要在StatefulWidget中管理,StatelessWidget无法触发setState更新。 - 图片尺寸未限制:图片过大可能导致布局溢出,进而显示空白。
- 依赖未安装:使用
GoogleFonts前需在pubspec.yaml添加依赖并执行flutter pub get。
方案一:调整CheckboxListTile实现横向布局
通过在title中嵌套Row,将图片和文字横向排列,同时保留CheckboxListTile的原生交互:
class CheckboxWithImage extends StatefulWidget { const CheckboxWithImage({super.key}); @override State<CheckboxWithImage> createState() => _CheckboxWithImageState(); } class _CheckboxWithImageState extends State<CheckboxWithImage> { bool _isChecked = false; @override Widget build(BuildContext context) { return CheckboxListTile( title: Row( children: [ // 限制图片尺寸,避免布局异常 Image.asset( 'images/image_1.png', width: 40, height: 40, fit: BoxFit.cover, ), const SizedBox(width: 12), // 用Expanded确保文字自适应宽度 Expanded( child: Text( 'lorem ipsum hby hweby fhr', style: GoogleFonts.poppins( color: const Color(0xff000000), fontSize: 15, letterSpacing: 0.4, ), ), ), ], ), value: _isChecked, onChanged: (bool? newValue) { setState(() { _isChecked = newValue ?? false; }); }, activeColor: const Color(0xff82b235), controlAffinity: ListTileControlAffinity.leading, // 复选框居左 ); } }
方案二:自定义Row布局(更灵活)
如果需要更自由的布局控制,可以直接用Row包裹Checkbox、图片和文字,搭配InkWell实现点击整行切换状态:
class CustomCheckboxRow extends StatefulWidget { const CustomCheckboxRow({super.key}); @override State<CustomCheckboxRow> createState() => _CustomCheckboxRowState(); } class _CustomCheckboxRowState extends State<CustomCheckboxRow> { bool _isChecked = false; @override Widget build(BuildContext context) { return InkWell( onTap: () => setState(() => _isChecked = !_isChecked), child: Padding( padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), child: Row( children: [ Checkbox( value: _isChecked, onChanged: (bool? newValue) { setState(() { _isChecked = newValue ?? false; }); }, activeColor: const Color(0xff82b235), ), const SizedBox(width: 12), Image.asset( 'images/image_1.png', width: 40, height: 40, fit: BoxFit.cover, ), const SizedBox(width: 12), Expanded( child: Text( 'lorem ipsum hby hweby fhr', style: GoogleFonts.poppins( color: const Color(0xff000000), fontSize: 15, letterSpacing: 0.4, ), ), ), ], ), ), ); } }
内容的提问来源于stack exchange,提问作者Priya
相关产品推荐
相关产品推荐

