Flutter自定义带删除线复选框删除线超出内容范围问题求解
问题原因
你当前写的删除线容器没有宽度限制,在Stack布局中默认会撑满父容器的最大可用宽度,所以会超出文字内容范围。
方案1(最简便,推荐):直接使用Text自带的删除线属性
不用在Stack里额外加删除线容器,直接修改Text的style配置即可,修改后的代码片段如下:
return GestureDetector( onTap: () { setState(() { _isSelected = !_isSelected; }); }, child: Row( mainAxisSize: MainAxisSize.min, children: [ AnimatedContainer( duration: Duration(milliseconds: 500), curve: Curves.fastLinearToSlowEaseIn, decoration: BoxDecoration( color: Colors.transparent, borderRadius: BorderRadius.circular(3.0), border: _isSelected ? null : Border.all( color: Colors.white, width: 1.0, )), width: widget.size, height: widget.size, ), SizedBox(width: 10), Text( widget.text, style: TextStyle( color: _isSelected ? Colors.grey : Colors.white, fontSize: 14, // 新增删除线配置 decoration: _isSelected ? TextDecoration.lineThrough : TextDecoration.none, decorationColor: Colors.grey, decorationThickness: 1, ), ), ], ), );
这个方案直接用Flutter原生文本样式能力,自动适配文本宽度,不会出现超出的问题,性能也更好。
方案2(如果必须自定义删除线容器的场景):限制删除线容器的宽度
给Stack套上IntrinsicWidth组件,让Stack的宽度自动适配子内容的实际宽度,再调整删除线的左边距跳过复选框区域:
return GestureDetector( onTap: () { setState(() { _isSelected = !_isSelected; }); }, child: Container( // 新增IntrinsicWidth限制Stack宽度仅匹配内容 child: IntrinsicWidth( child: Stack(alignment: Alignment.centerLeft, children: [ Row( mainAxisSize: MainAxisSize.min, children: [ AnimatedContainer( duration: Duration(milliseconds: 500), curve: Curves.fastLinearToSlowEaseIn, decoration: BoxDecoration( color: Colors.transparent, borderRadius: BorderRadius.circular(3.0), border: _isSelected ? null : Border.all( color: Colors.white, width: 1.0, )), width: widget.size, height: widget.size, ), SizedBox(width: 10), Text( widget.text, style: TextStyle( color: _isSelected ? Colors.grey : Colors.white, fontSize: 14), ), ], ), _isSelected ? Container( // 新增左边距,跳过复选框和间隔区域 margin: EdgeInsets.only(left: widget.size + 10), height: 1, color: Colors.grey, ) : SizedBox.shrink(), // 替换空Container更规范 ]), ), ), );
内容的提问来源于stack exchange,提问作者Ivan
相关产品推荐
相关产品推荐

