이수연의 티스토리
[Flutter] TextField 오버플로우 문제와 해결! 본문
오늘은 Flutter에서 TextField를 사용할 때 발생하는 오버플로우(overflow) 문제는 플러터 초보들에게 자주 발생하는 문제중 하나이다.
특히 Container 안에 TextField를 감싸거나, 긴 hintText를 사용할 때 쉽게 발생한다.
그래서 오늘은
1. TextField에서 오버플로우가 발생하는 이유
2.수정 코드를 통해 오버플로우를 방지하는 예시를 설명
📌 문제 상황: TextFied의 오버플로우 발생
다음과 같은 코드를 작성하면 오버플로우 오류가 발생한다!
Expanded(
child: Container(
height: 51,
padding: const EdgeInsets.symmetric(
horizontal: 14,
vertical: 18,
),
decoration: ShapeDecoration(
color: Color(0xFFF2F2F2),
shape: RoundedRectangleBorder(
side: BorderSide(
width: 1,
color: Color(0xFFB3B3B3),
),
borderRadius: BorderRadius.circular(6),
),
),
child: TextField(
controller: _emailController,
maxLines: 1,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
hint: FittedBox(
fit: BoxFit.scaleDown,
alignment: Alignment.centerLeft,
child: Text(
'Hello World! Hello World! Hello World!',
style: TextStyle(
color: Color(0xFF999999),
fontSize: 14,
fontFamily: 'Pretendard',
fontWeight: FontWeight.w400,
letterSpacing: -1,
),
),
),
border: InputBorder.none,
),
textAlign: TextAlign.start,
),
),
),
이렇게 된다면 텍스트 박스를 넘어가는 글자가 생기며 텍스트 박스 안에 있는 글자가 보이지 않게 된다.
📌 왜 오버플로우가 발생했을까?
1. container가 자식 위젯에 크기를 강제
- Container는 자식의 크기를 제한하는데, TextField는 내부적으로 무한한 크기를 가지려는 성질이 있다.
- 두 속성이 충돌하면서 오버플로우가 발생한다!
2.중복된 패딩(padding) 문제
- Container의 padding과 TextField의 contentPadding이 중복되어 내부 요소의 크기가 커진다.
3. FittedBox의 잘못된 작성
- InputDecoraion의 hint는 TextField의 레이아웃 시스템과 잘 맞지 않는다. FittedBox는 자식의 크기를 조절하지만, TextField는 이를 제대로 반영하지 않는다.
✅해결 방법 : 수정 코드
Expanded(
child: Container(
height: 51,
padding: const EdgeInsets.symmetric(
horizontal: 14,
vertical: 0, // 중복 패딩 제거
),
decoration: ShapeDecoration(
color: Color(0xFFF2F2F2),
shape: RoundedRectangleBorder(
side: BorderSide(
width: 1,
color: Color(0xFFB3B3B3),
),
borderRadius: BorderRadius.circular(6),
),
),
child: Align(
alignment: Alignment.centerLeft, // 힌트 정렬 문제 해결
child: TextField(
controller: _emailController,
maxLines: 1,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
hintText: 'Hello World! Hello World! Hello World!',
hintStyle: TextStyle(
color: Color(0xFF999999),
fontSize: 14,
fontFamily: 'Pretendard',
fontWeight: FontWeight.w400,
letterSpacing: -1,
),
border: InputBorder.none,
contentPadding: EdgeInsets.zero, // 중복 패딩 제거
),
textAlign: TextAlign.start,
),
),
),
),
✅ 오버플로우가 발생하지 않는 이유?
1. Align으로 TextFiedl 정렬
- TextField는 내부적으로 정렬을 제대로 수행하지 못하므로 Align으로 감싸서 위치를 명시한다.
2. contenePadding: EdgeInsets.zero로 중복 제거
- Container의 padding과 TextField의 contenePadding을 중복으로 적용하지 않도록 수정했다.
3.hintText 사용
- hint 대신 hintText를 사용해 Flutter의 기본 제공 방식을 따른다. hint는 위젯을 받을 수 있지만 레이아웃에서 예상치 못한 문제가 발생할 수 있다.
'flutter' 카테고리의 다른 글
플러터 2장 UI에 사용되는 위젯 제대로 파악하기! (0) | 2025.02.17 |
---|---|
플러터 1장 다양한 위젯 사용! (0) | 2025.02.15 |
[DO it! 1인 개발로 플러터 앱 만들기] 1장 - 다트 언어 실습 (0) | 2025.02.06 |
[DO it! 1인 개발로 플러터 앱 만들기] 1장 - 플러터와 다트 기초 다지기 (0) | 2025.02.04 |