텍스트가 overflow
된 경우, ...
이 나오도록 ellipsis
를 설정할 수 있으나, ...
이 아니라 더보기
와 같은 custion ellipsis
를 주고 싶을 때가 있다. 이때 다소 복잡한 방법이지만 TextPainter
와 CustomPainter
를 활용하여 커스텀 ellipsis
가 적용된 Text
위젯을 만들 수 있다.
import 'package:flutter/material.dart';
class CustomEllipsisText extends StatelessWidget {
const CustomEllipsisText({
Key? key,
required this.text,
this.style,
required this.ellipsis,
this.maxWidth = double.infinity,
this.minWidth = 0,
this.maxLines = 1,
this.textDirection,
}) : super(key: key);
final String text;
final TextStyle? style;
final String ellipsis;
final int maxLines;
final double maxWidth, minWidth;
final TextDirection? textDirection;
Widget build(BuildContext context) {
TextPainter textPainter = TextPainter(
text: TextSpan(text: text, style: style),
maxLines: maxLines,
textDirection: textDirection ?? TextDirection.ltr,
)..layout(minWidth: minWidth, maxWidth: maxWidth);
return CustomPaint(
size: textPainter.size,
painter: _CustomEllipsisTextPainter(
text: TextSpan(text: text, style: style),
ellipsis: ellipsis,
maxLines: maxLines,
));
}
}
class _CustomEllipsisTextPainter extends CustomPainter {
final TextSpan text;
final int maxLines;
final String ellipsis;
_CustomEllipsisTextPainter({
required this.text,
required this.ellipsis,
required this.maxLines,
}) : super();
bool shouldRepaint(CustomPainter oldDelegate) => false;
void paint(Canvas canvas, Size size) {
TextPainter painter = TextPainter(
text: text,
maxLines: maxLines,
textDirection: TextDirection.ltr,
)..ellipsis = ellipsis;
painter.layout(maxWidth: size.width);
painter.paint(canvas, const Offset(0, 0));
}
}
코드 참고 : Flutter에서 텍스트 확장