【发布时间】:2023-02-15 22:46:30
【问题描述】:
这是必需的小部件
我试过使用堆栈。但没有得到正确的解决方案
【问题讨论】:
-
你指的是不同的文字颜色吗?
-
不,我想创建一个这样的小部件。主要是我被卡住的是,我想延长下划线和厚度直到文本区域
-
您可以尝试仅使用容器边框底部,或文本装饰下划线
这是必需的小部件
我试过使用堆栈。但没有得到正确的解决方案
【问题讨论】:
您可以首先实现这一点,您需要计算文本小部件以使用 TextPainter 和 LayoutBuilder 绘制具有相同文本宽度的蓝色下划线:
class TextPainterWidget extends StatelessWidget {
final TextPainter textPainter;
const TextPainterWidget({
Key? key,
required this.textPainter,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return CustomPaint(
painter: _TextPainterWidget(textPainter),
);
}
}
class _TextPainterWidget extends CustomPainter {
final TextPainter textPainter;
_TextPainterWidget(this.textPainter);
@override
void paint(Canvas canvas, Size size) {
textPainter.layout();
textPainter.paint(canvas, Offset.zero);
}
@override
bool shouldRepaint(_TextPainterWidget oldDelegate) {
return oldDelegate.textPainter.text != textPainter.text ||
oldDelegate.textPainter.text?.style != textPainter.text?.style;
}
}
那么你的主要小部件应该是这样的:
LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
final TextPainter textPainter = TextPainter(
text: const TextSpan(
text: 'Grab The Best Deal On ',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
),
children: <TextSpan>[
TextSpan(
text: 'Smartphones',
style: TextStyle(
color: Colors.blue,
fontWeight: FontWeight.bold,
),
),
],
),
textDirection: TextDirection.ltr,
)..layout(maxWidth: constraints.maxWidth);
final double textWidth = textPainter.width;
return Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
TextPainterWidget(textPainter: textPainter),
Row(
children: <Widget>[
const Text('View All'),
const SizedBox(width: 8),
InkWell(
onTap: () {},
child: const Icon(
Icons.arrow_forward_ios,
size: 15,
color: Colors.blue,
),
),
],
),
],
),
Row(
children: <Widget>[
SizedBox(
width: textWidth,
child: const Divider(
color: Colors.blue,
thickness: 2,
),
),
const Expanded(
child: Divider(
color: Colors.grey,
thickness: 1,
),
),
],
),
],
);
},
),
【讨论】: