Last active
December 29, 2023 06:32
-
-
Save Origogi/41387c1cde2c38e4fc3cd811f2634a5c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
class DynamicTextView extends StatelessWidget { | |
final String nickname; | |
final String postfix; | |
const DynamicTextView({ | |
Key? key, | |
required this.nickname, | |
required this.postfix, | |
}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return LayoutBuilder( | |
builder: (BuildContext context, BoxConstraints constraints) { | |
final maxWidth = constraints.maxWidth * 2 - 20; | |
final testPaint = TextPainter( | |
textDirection: TextDirection.ltr, | |
text: TextSpan(text: nickname + postfix), | |
)..layout(); | |
String displayText = ""; | |
if (testPaint.size.width > maxWidth) { | |
// 여기서 닉네임을 줄임 처리해야 함 | |
int nicknameLength = nickname.length; | |
while (nicknameLength > 0) { | |
final ellipsisText = TextPainter( | |
textDirection: TextDirection.ltr, | |
text: TextSpan(text: nickname.substring(0, nicknameLength) + '...' + postfix), | |
)..layout(); | |
if (ellipsisText.size.width <= maxWidth) { | |
displayText = nickname.substring(0, nicknameLength) + '...' + postfix; | |
break; | |
} | |
nicknameLength--; | |
} | |
} else { | |
displayText = nickname + postfix; | |
} | |
return Text( | |
displayText, | |
maxLines : 2 | |
); | |
}, | |
); | |
} | |
} | |
void main() { | |
runApp( | |
MaterialApp( | |
home: Scaffold( | |
body: Center( | |
child: Container( | |
width : 100, | |
color : Colors.amber, | |
child: DynamicTextView( | |
nickname: 'abcdeabcdeabcdeabcdeabcdeabcde', | |
postfix: ' like you!', | |
), | |
), | |
), | |
), | |
), | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment