티스토리 뷰
Flutter에서 텍스트 필드에 입력된 값을 가져오는 방법은 폼 데이터를 관리하고 사용자 입력을 처리하는 데 매우 중요합니다. TextEditingController
를 활용해 사용자가 입력한 텍스트를 실시간으로 가져오는 방법을 살펴보겠습니다. 이는 Flutter에서 폼 처리, 사용자 입력 검증 등 다양한 상황에서 유용하게 활용할 수 있습니다.
참고. Retrieve the value of a text field
Flutter 텍스트 필드 입력값을 가져오는 방법
Flutter에서 텍스트 필드의 현재 값을 가져오는 가장 효과적인 방법은 TextEditingController
를 사용하는 것입니다. 이 컨트롤러는 텍스트 필드와 연결되어 사용자가 입력한 값을 실시간으로 추적하고, 이를 통해 다양한 작업을 수행할 수 있습니다. 아래에서는 이를 단계별로 구현하는 방법을 설명합니다.
1. TextEditingController 생성하기
TextEditingController
는 입력값을 관리하는 컨트롤러로, 텍스트 필드에 입력된 값을 쉽게 가져올 수 있게 합니다. 상태를 지속적으로 추적해야 하므로, 일반적으로 StatefulWidget
내부에서 사용합니다.
class MyCustomForm extends StatefulWidget {
const MyCustomForm({super.key});
@override
State<MyCustomForm> createState() => _MyCustomFormState();
}
class _MyCustomFormState extends State<MyCustomForm> {
final myController = TextEditingController();
@override
void dispose() {
// 컨트롤러를 정리하여 메모리 누수를 방지합니다.
myController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return TextField(
controller: myController,
);
}
}
Tip:
TextEditingController
는 위젯이 사라질 때 반드시dispose()
메서드를 호출하여 정리해야 합니다. 이를 통해 메모리 누수를 방지할 수 있습니다.
2. TextEditingController를 TextField와 연결하기
이제 TextEditingController
를 텍스트 필드에 연결하여 사용자가 입력한 값을 가져올 수 있도록 합니다. 이를 위해 텍스트 필드의 controller
속성에 myController
를 할당합니다.
TextField(
controller: myController,
),
이제 myController
를 통해 텍스트 필드의 현재 값을 실시간으로 가져올 수 있습니다.
3. 텍스트 필드의 현재 값 표시하기
사용자가 텍스트 필드에 입력한 값을 화면에 표시하거나, 특정 작업을 수행할 때 사용할 수 있습니다. 예를 들어, 버튼을 클릭하면 입력된 값을 확인하는 알림창을 띄울 수 있습니다.
FloatingActionButton(
onPressed: () {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
// TextEditingController를 사용해 입력된 텍스트를 가져와 표시합니다.
content: Text(myController.text),
);
},
);
},
tooltip: '현재 입력된 텍스트 보기',
child: const Icon(Icons.text_fields),
),
위 코드는 플로팅 액션 버튼을 눌렀을 때 알림창에 현재 입력된 텍스트 필드의 값을 표시하는 예시입니다. 이를 통해 사용자 입력을 확인하고 다양한 액션을 수행할 수 있습니다.
TextEditingController 활용 예시
실시간 검색 기능 구현
검색창에서 입력할 때마다 결과를 업데이트하거나, 입력한 내용에 맞춰 추천 항목을 표시하는 기능을 구현할 수 있습니다. TextEditingController
를 통해 입력값을 추적하고, 필터링된 결과를 실시간으로 보여줄 수 있습니다.
폼 검증과 데이터 처리
폼을 작성할 때, TextEditingController
로 입력값을 가져와 즉시 유효성 검사를 수행하고, 사용자가 잘못된 값을 입력했을 때 안내 메시지를 보여주는 등의 기능을 구현할 수 있습니다.
데이터 초기화와 동적 업데이트
특정 이벤트 발생 시 텍스트 필드를 초기화하거나, 특정 조건에 따라 필드 값을 동적으로 변경할 수 있습니다. 예를 들어, myController.text = "초기값";
과 같이 사용해 필드의 값을 프로그래밍적으로 설정할 수 있습니다.
Flutter에서 텍스트 필드 관리의 장점
Flutter에서 TextEditingController
를 활용해 텍스트 필드를 제어하면 다음과 같은 장점이 있습니다.
- 간편한 데이터 추적: 사용자 입력을 쉽게 가져와 다양한 작업을 수행할 수 있습니다.
- 유연한 데이터 처리: 실시간으로 데이터를 처리하거나 변경할 수 있어 동적인 사용자 인터페이스를 구성할 수 있습니다.
- 메모리 관리 가능:
dispose()
메서드를 통해 메모리 누수를 방지하고 앱 성능을 최적화할 수 있습니다.
TextEditingController
는 Flutter에서 텍스트 필드를 효율적으로 제어하고 데이터를 처리하는 데 매우 유용한 도구입니다. 간단한 폼에서부터 복잡한 입력 검증까지, 다양한 상황에서 활용해보세요.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Retrieve Text Input',
home: MyCustomForm(),
);
}
}
// Define a custom Form widget.
class MyCustomForm extends StatefulWidget {
const MyCustomForm({super.key});
@override
State<MyCustomForm> createState() => _MyCustomFormState();
}
// Define a corresponding State class.
// This class holds the data related to the Form.
class _MyCustomFormState extends State<MyCustomForm> {
// Create a text controller and use it to retrieve the current value
// of the TextField.
final myController = TextEditingController();
@override
void dispose() {
// Clean up the controller when the widget is disposed.
myController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Retrieve Text Input'),
),
body: Padding(
padding: const EdgeInsets.all(16),
child: TextField(
controller: myController,
),
),
floatingActionButton: FloatingActionButton(
// When the user presses the button, show an alert dialog containing
// the text that the user has entered into the text field.
onPressed: () {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
// Retrieve the text the that user has entered by using the
// TextEditingController.
content: Text(myController.text),
);
},
);
},
tooltip: 'Show me the value!',
child: const Icon(Icons.text_fields),
),
);
}
}
'Flutter Cookbook' 카테고리의 다른 글
Flutter로 Firestore를 활용한 멀티플레이어 게임 구현하기 (1) | 2024.11.08 |
---|---|
플러터로 게임 리더보드와 업적 시스템 구축하기 (1) | 2024.11.07 |
Flutter에서 텍스트 필드 변경 사항 감지하기: 실시간 입력 제어의 모든 것 (3) | 2024.11.06 |
Flutter에서 텍스트 필드 포커스 관리하기: 효과적인 사용자 경험 만들기 (2) | 2024.11.05 |
Flutter에서 텍스트 입력 필드 구현 및 스타일링 방법 (1) | 2024.11.04 |