728x90
Flutter의 Text 위젯에서 사용할 수 있는 주요 스타일은 TextStyle 클래스를 통해 지정됩니다.
✅ TextStyle 속성 정리 표
속성 | 타입 | 설명 |
color | Color | 글자 색상 |
fontSize | double | 글자 크기 |
fontWeight | FontWeight | 글자 두께 (w100~w900, bold) |
fontStyle | FontStyle | 이탤릭 여부 (italic, normal) |
letterSpacing | double | 자간 (글자 사이 간격) |
wordSpacing | double | 단어 사이 간격 |
height | double | 줄 간격 (line height, fontSize 대비 배율) |
backgroundColor | Color | 배경 색상 |
decoration | TextDecoration | 밑줄, 취소선, 윗줄 (underline, lineThrough, overline) |
decorationColor | Color | 데코레이션 색상 |
decorationStyle | TextDecorationStyle | 데코 선 스타일 (solid, dashed, dotted 등) |
decorationThickness | double | 데코 선 두께 |
fontFamily | String | 글꼴 이름 (e.g., "Roboto") |
shadows | List<Shadow> | 그림자 효과 |
overflow | TextOverflow | 텍스트 넘칠 때 처리 (ellipsis, fade, clip) |
textBaseline | TextBaseline | 기준선 정렬 (alphabetic, ideographic) |
locale | Locale | 지역 언어 설정 |
foreground | Paint | 글자에 직접 색상이나 효과를 칠할 때 |
background | Paint | 배경을 직접 그릴 때 |
🧪 예시 코드
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(
home: Scaffold(
body: Center(
child: StyledTextExample(),
),
),
));
}
class StyledTextExample extends StatelessWidget {
const StyledTextExample({super.key});
@override
Widget build(BuildContext context) {
return Text(
'Flutter Text 스타일 예제 ✨',
style: TextStyle(
color: Colors.indigo, // 글자색
fontSize: 24, // 글자 크기
fontWeight: FontWeight.bold, // 두껍게
fontStyle: FontStyle.italic, // 이탤릭체
letterSpacing: 2.0, // 자간
wordSpacing: 8.0, // 단어 간격
height: 1.5, // 줄 간격
backgroundColor: Colors.yellow[100], // 배경색
decoration: TextDecoration.underline, // 밑줄
decorationColor: Colors.indigo, // 밑줄 색상
decorationStyle: TextDecorationStyle.dashed, // 밑줄 스타일
decorationThickness: 2.0, // 밑줄 두께
fontFamily: 'Roboto', // 글꼴
shadows: [
Shadow(
color: Colors.grey,
offset: Offset(2, 2),
blurRadius: 4,
),
],
),
);
}
}
🎯 팁
- overflow: TextOverflow.ellipsis 등을 Text 위젯에 직접 설정하여 글자 잘림 처리 가능.
- maxLines: 1과 함께 쓰면 긴 텍스트를 한 줄에 자르고 ... 처리할 수 있음.
- 커스텀 폰트를 쓰려면 pubspec.yaml에 등록해야 함.
+
✅ 커스텀 폰트 적용 방법
📌 1단계: fonts 폴더 생성
프로젝트 루트에 assets/fonts/ 폴더를 만들고 원하는 폰트 파일을 복사해 넣는다. 예:
assets/fonts/NanumSquareRoundR.ttf
📌 2단계: pubspec.yaml 등록
flutter:
fonts:
- family: NanumSquareRound
fonts:
- asset: assets/fonts/NanumSquareRoundR.ttf
※ flutter: 아래에 들여쓰기 정확히 맞춰야 함 (2칸씩).
📌 3단계: 코드에서 사용
Text(
'커스텀 폰트 적용 예제',
style: TextStyle(
fontFamily: 'NanumSquareRound',
fontSize: 24,
),
)
📝 팁
- 여러 굵기(Bold, Light)가 있을 경우 weight 속성으로 구분 가능:
- family: NanumSquareRound
fonts:
- asset: assets/fonts/NanumSquareRoundL.ttf
weight: 300
- asset: assets/fonts/NanumSquareRoundR.ttf
weight: 400
- asset: assets/fonts/NanumSquareRoundB.ttf
weight: 700
그럼 fontWeight: FontWeight.w700 식으로 적용 가능.
✅ 여러 스타일을 혼합한 리치 텍스트 (RichText, TextSpan)
Text 위젯은 한 번에 하나의 스타일만 적용 가능하지만, RichText와 TextSpan을 사용하면 한 문장 안에 다양한 스타일을 부분적으로 적용할 수 있어.
📌 예제 코드
RichText(
text: TextSpan(
style: const TextStyle(fontSize: 18, color: Colors.black),
children: [
const TextSpan(text: '안녕하세요, '),
TextSpan(
text: '송솔',
style: const TextStyle(
color: Colors.blue,
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
const TextSpan(text: '님! 오늘도 '),
TextSpan(
text: '화이팅 💪',
style: const TextStyle(
color: Colors.redAccent,
fontStyle: FontStyle.italic,
),
),
],
),
)
📝 RichText 사용 시 주의점
- RichText는 textAlign, maxLines 등 일부 속성은 직접 처리해줘야 함.
- GestureRecognizer를 통해 부분 클릭 이벤트도 가능.
TextSpan(
text: '여기를 클릭',
style: TextStyle(color: Colors.blue),
recognizer: TapGestureRecognizer()..onTap = () {
print('클릭됨!');
},
)
✅ RichText에서 클릭 가능한 하이퍼링크 구현
TextSpan에 TapGestureRecognizer를 넣으면 특정 텍스트에 클릭 이벤트를 부여할 수 있어. 하이퍼링크처럼 동작하게 만들 수 있음.
📌 필수: 리소스 해제(dispose())가 필요하기 때 에 TapGestureRecognizer는 StatefulWidget에서 사용 권장
리소스 해제(dispose())가 필요하기 때문.
✅ 예제 코드: 하이퍼링크 텍스트
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
class RichTextLinkExample extends StatefulWidget {
const RichTextLinkExample({super.key});
@override
State createState() => _RichTextLinkExampleState();
}
class _RichTextLinkExampleState extends State {
final TapGestureRecognizer _tapRecognizer = TapGestureRecognizer();
@override
void dispose() {
_tapRecognizer.dispose();
super.dispose();
}
void _launchURL() async {
final url = Uri.parse("https://flutter.dev");
if (await canLaunchUrl(url)) {
await launchUrl(url, mode: LaunchMode.externalApplication);
}
}
@override
Widget build(BuildContext context) {
return Center(
child: RichText(
text: TextSpan(
style: const TextStyle(color: Colors.black, fontSize: 16),
children: [
const TextSpan(text: '자세한 정보는 '),
TextSpan(
text: 'flutter.dev',
style: const TextStyle(
color: Colors.blue,
decoration: TextDecoration.underline,
),
recognizer: _tapRecognizer..onTap = _launchURL,
),
const TextSpan(text: '에서 확인하세요!'),
],
),
),
);
}
}
📌 의존성 추가 (url_launcher)
dependencies:
url_launcher: ^6.2.5
flutter pub get
✅ 커스텀 아이콘 폰트 추가 방법 (ex. FontAwesome, custom.ttf)
아이콘 폰트는 일반 폰트처럼 추가하지만, 사용은 IconData를 통해 해야 함.
📌 1단계: TTF 파일 준비
예: assets/fonts/MyIcons.ttf
📌 2단계: pubspec.yaml 등록
flutter:
fonts:
- family: MyIcons
fonts:
- asset: assets/fonts/MyIcons.ttf
📌 3단계: 유니코드 확인
폰트 제작자 또는 IcoMoon 등에서 확인 가능. 예: 0xe900
📌 4단계: 코드에서 사용
Icon(
IconData(0xe900, fontFamily: 'MyIcons'),
size: 32,
color: Colors.teal,
)
📌 IconData는 유니코드 값을 16진수로 넣어야 함.
🧠 팁
- IcoMoon에서 원하는 아이콘을 선택해 직접 .ttf를 생성하면 쉽게 커스텀 아이콘 세트를 만들 수 있음.
- 여러 개의 폰트를 혼용하려면 Text.rich() 또는 RichText() + Icon()을 조합해 사용.
'Flutter + Dart > Flutter + Dart TIP' 카테고리의 다른 글
Dart(및 Flutter) 언어에서 사용되는 주요 키워드/수식어(modifier)/식별자(reserved identifiers) (0) | 2025.05.16 |
---|---|
flutter 모듈화 (0) | 2025.05.15 |
Flutter 위젯 카탈로그 (0) | 2025.05.13 |
Container에서 테두리를 만드는 방법 (0) | 2025.05.13 |
기타 (0) | 2025.05.13 |