본문 바로가기
프로그래밍/Flutter

[ Flutter Widget ] 플러터 기본위젯 - Textfield

by 호랑이탈 2025. 1. 1.
반응형

Flutter 기본위젯 - TextField 위젯

Flutter의 Textfield는 사용자가 텍스트를 입력할 수 있는 필드를 제공하는 가장 기본적인 위젯입니다.

이 위젯은 다양한 매개변수를 통해서 사용자입력, 스타일을 세세하게 제어할 수 있습니다.

 

Textfield() 함수 원형

const TextField({
  Key? key,
  TextEditingController? controller,
  FocusNode? focusNode,
  InputDecoration? decoration = const InputDecoration(),
  TextInputType? keyboardType,
  TextCapitalization textCapitalization = TextCapitalization.none,
  TextInputAction? textInputAction,
  TextStyle? style,
  StrutStyle? strutStyle,
  TextAlign textAlign = TextAlign.start,
  TextAlignVertical? textAlignVertical,
  bool autofocus = false,
  bool readOnly = false,
  bool showCursor,
  String obscuringCharacter = '•',
  bool obscureText = false,
  bool autocorrect = true,
  SmartDashesType? smartDashesType,
  SmartQuotesType? smartQuotesType,
  bool enableSuggestions = true,
  int? maxLines = 1,
  int? minLines,
  bool expands = false,
  int? maxLength,
  MaxLengthEnforcement? maxLengthEnforcement,
  ValueChanged<String>? onChanged,
  GestureTapCallback? onTap,
  ValueChanged<String>? onEditingComplete,
  ValueChanged<String>? onSubmitted,
  List<TextInputFormatter>? inputFormatters,
  bool enabled,
  double cursorWidth = 2.0,
  double? cursorHeight,
  Radius? cursorRadius,
  Color? cursorColor,
  Brightness? keyboardAppearance,
  EdgeInsets scrollPadding = const EdgeInsets.all(20.0),
  DragStartBehavior dragStartBehavior = DragStartBehavior.start,
  bool enableInteractiveSelection = true,
  TextSelectionControls? selectionControls,
  InputCounterWidgetBuilder? buildCounter,
  ScrollPhysics? scrollPhysics,
  ScrollController? scrollController,
  Iterable<String>? autofillHints,
  Clip clipBehavior = Clip.hardEdge,
})

 

 

 
1. controller

  • TextEditingController를 사용하여 입력된 텍스트를 제어하거나 가져옵니다.
  • 타입: TextEditingController?
TextEditingController myController = TextEditingController();
TextField(controller: myController);

 

2. focusNode

  • 텍스트 필드의 포커스를 제어합니다.
  • 타입: FocusNode?


3. decoration

  • 텍스트 필드의 외형과 레이블, 힌트 등을 꾸밀 수 있습니다.
  • 타입: InputDecoration?
decoration: InputDecoration(
  labelText: 'Enter your name',
  border: OutlineInputBorder(),
);


4. keyboardType

  • 텍스트 입력 시 나타나는 키보드의 유형을 지정합니다.
  • 타입: TextInputType?
    • TextInputType.text: 일반 텍스트.
    • TextInputType.number: 숫자 입력.
    • TextInputType.emailAddress: 이메일 입력 등.

 


5. obscureText

  • 텍스트를 비밀번호처럼 가립니다.
  • 타입: bool
  • 기본값: false


6. maxLines & minLines

  • 텍스트 필드에서 입력 가능한 줄 수를 제어합니다.
  • 타입: int?

 

7. onChanged

  • 텍스트가 변경될 때 호출되는 콜백 함수.
  • 타입: ValueChanged<String>?

 

8. onSubmitted

  • 사용자가 "완료"를 누를 때 호출됩니다.
  • 타입: ValueChanged<String>?

 

9. cursorColor

  • 커서 색상을 지정합니다.
  • 타입: Color?

 

10. autofocus

  • 화면이 로드되자마자 자동으로 포커스를 받을지 여부를 결정합니다.
  • 타입: bool
  • 기본값: false

 

11. textCapitalization

  • 텍스트 입력 시 자동으로 대소문자를 변경하는 방식을 설정합니다.
  • 타입: TextCapitalization
  • 기본값: TextCapitalization.none
    • TextCapitalization.none: 대소문자 변경 없음.
    • TextCapitalization.words: 각 단어의 첫 글자를 대문자로.
    • TextCapitalization.sentences: 각 문장의 첫 글자를 대문자로.
    • TextCapitalization.characters: 모든 문자를 대문자로.

12. textAlignVertical

  • 텍스트 필드의 수직 정렬을 설정합니다.
  • 타입: TextAlignVertical?
    • TextAlignVertical.top: 위쪽 정렬.
    • TextAlignVertical.center: 가운데 정렬.
    • TextAlignVertical.bottom: 아래쪽 정렬.

 

13. readOnly

  • 텍스트 필드를 읽기 전용으로 설정합니다. 사용자는 텍스트를 입력하거나 수정할 수 없습니다.
  • 타입: bool
  • 기본값: false

 

14. showCursor

  • 텍스트 필드에서 커서를 표시할지 여부를 결정합니다.
  • 타입: bool?

15. obscuringCharacter

  • 텍스트를 숨길 때 표시할 문자입니다. 기본값은 •입니다.
  • 타입: String


16. autocorrect

  • 자동 수정 기능을 사용할지 여부를 설정합니다.
  • 타입: bool
  • 기본값: true


17. smartDashesType

  • 스마트 대시(–) 기능을 설정합니다.
  • 타입: SmartDashesType?
  • 18. smartQuotesType
  • 스마트 따옴표 기능을 설정합니다.
  • 타입: SmartQuotesType?

 

19. enableSuggestions

  • 텍스트 입력 중 제안(자동 완성)을 활성화할지 여부를 설정합니다.
  • 타입: bool
  • 기본값: true

 

20. expands

  • 텍스트 필드가 부모 위젯의 크기에 맞게 확장될지 여부를 설정합니다.
  • 타입: bool
  • 기본값: false

 

21. maxLength

  • 입력 가능한 최대 문자 수를 지정합니다.
  • 타입: int?


22. maxLengthEnforcement

  • maxLength 초과 시 동작 방식을 설정합니다.
  • 타입: MaxLengthEnforcement?
    • MaxLengthEnforcement.enforced: 초과 입력 불가.
    • MaxLengthEnforcement.none: 초과 입력 허용.


23. inputFormatters

  • 사용자 입력을 필터링하거나 변환하는 데 사용됩니다.
  • 타입: List<TextInputFormatter>?

 

24. enabled

  • 텍스트 필드의 활성화/비활성화 상태를 설정합니다.
  • 타입: bool?


25. cursorWidth

  • 커서의 두께를 설정합니다.
  • 타입: double
  • 기본값: 2.0


26. cursorHeight

  • 커서의 높이를 설정합니다.
  • 타입: double?

 

27. cursorRadius

  • 커서의 모서리를 둥글게 설정합니다.
  • 타입: Radius?

 

28. keyboardAppearance

  • 키보드의 밝기를 설정합니다.
  • 타입: Brightness?
    • Brightness.light: 밝은 키보드.
    • Brightness.dark: 어두운 키보드.

 

29. scrollPadding

  • 스크롤 시 텍스트 필드 주변의 여백을 설정합니다.
  • 타입: EdgeInsets


30. dragStartBehavior

  • 드래그 시작 동작을 설정합니다.
  • 타입: DragStartBehavior

 

31. enableInteractiveSelection

  • 텍스트 선택 및 복사/잘라내기 기능 활성화 여부를 설정합니다.
  • 타입: bool
  • 기본값: true

 

32. selectionControls

  • 커스텀 텍스트 선택 컨트롤을 정의합니다.
  • 타입: TextSelectionControls?

 

33. scrollPhysics

  • 스크롤 동작의 물리적 속성을 설정합니다.
  • 타입: ScrollPhysics?

 

34. autofillHints

  • 자동 완성 힌트를 제공합니다.
  • 타입: Iterable<String>?


35. clipBehavior

  • 텍스트 필드가 부모 위젯 경계를 넘어갈 경우의 동작을 설정합니다.
  • 타입: Clip

 

샘플예제

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('TextField Full Example'),
        ),
        body: const Padding(
          padding: EdgeInsets.all(16.0),
          child: MyTextFieldExample(),
        ),
      ),
    );
  }
}

class MyTextFieldExample extends StatefulWidget {
  const MyTextFieldExample({super.key});

  @override
  _MyTextFieldExampleState createState() => _MyTextFieldExampleState();
}

class _MyTextFieldExampleState extends State<MyTextFieldExample> {
  final TextEditingController _controller = TextEditingController(); // 텍스트를 제어하기 위한 컨트롤러
  final FocusNode _focusNode = FocusNode(); // 포커스 상태를 제어하기 위한 포커스 노드

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        TextField(
          controller: _controller, // 입력된 텍스트를 제어
          focusNode: _focusNode, // 텍스트 필드의 포커스를 제어
          decoration: InputDecoration(
            labelText: 'Your Name', // 필드의 레이블 텍스트
            hintText: 'Enter your name', // 필드의 힌트 텍스트
            prefixIcon: Icon(Icons.person), // 필드 앞에 아이콘 추가
            suffixIcon: IconButton(
              icon: Icon(Icons.clear), // 텍스트를 지우는 버튼
              onPressed: () {
                _controller.clear(); // 컨트롤러를 사용해 텍스트 초기화
              },
            ),
            border: OutlineInputBorder(), // 테두리 스타일 설정
            helperText: 'Name must be alphabetic', // 사용자 도움말 텍스트
            counterText: '', // 입력된 길이 표시 숨김
          ),
          keyboardType: TextInputType.text, // 텍스트 입력 시 일반 키보드 사용
          textCapitalization: TextCapitalization.words, // 단어의 첫 글자 대문자로
          textInputAction: TextInputAction.done, // 키보드에서 "완료" 버튼 표시
          style: TextStyle(fontSize: 18, color: Colors.black), // 텍스트 스타일 설정
          textAlign: TextAlign.left, // 텍스트를 왼쪽 정렬
          textAlignVertical: TextAlignVertical.center, // 텍스트를 필드 중앙 정렬
          autofocus: true, // 화면 로드 시 자동으로 포커스
          readOnly: false, // 읽기 전용으로 설정하지 않음
          obscureText: false, // 텍스트를 숨기지 않음
          obscuringCharacter: '*', // 숨길 경우 대체 문자 설정
          autocorrect: true, // 자동 수정 기능 활성화
          smartDashesType: SmartDashesType.enabled, // 스마트 대시 활성화
          smartQuotesType: SmartQuotesType.enabled, // 스마트 따옴표 활성화
          enableSuggestions: true, // 자동 완성 기능 활성화
          maxLines: 1, // 한 줄로 제한
          minLines: 1, // 최소 줄 수 설정
          expands: false, // 부모 위젯 크기에 맞게 확장하지 않음
          maxLength: 20, // 최대 입력 길이 설정
          maxLengthEnforcement: MaxLengthEnforcement.enforced, // 최대 길이 초과 입력 제한
          onChanged: (value) {
            // 텍스트 변경 시 호출
            print('Text changed: $value');
          },
          onSubmitted: (value) {
            // 사용자가 완료 버튼을 누를 때 호출
            print('Text submitted: $value');
          },
          cursorColor: Colors.blue, // 커서 색상 설정
          cursorWidth: 2.0, // 커서 두께 설정
          cursorRadius: Radius.circular(4.0), // 커서 모서리 둥글게 설정
          inputFormatters: [
            // 입력 포맷터 설정
            FilteringTextInputFormatter.allow(RegExp("[a-zA-Z ]")), // 알파벳 및 공백만 허용
          ],
          scrollPadding: EdgeInsets.all(20.0), // 스크롤 여백 설정
          dragStartBehavior: DragStartBehavior.start, // 드래그 시작 동작 설정
          enableInteractiveSelection: true, // 텍스트 선택 활성화
          keyboardAppearance: Brightness.light, // 키보드 밝기 설정
          scrollPhysics: BouncingScrollPhysics(), // 스크롤 물리 설정
          autofillHints: [AutofillHints.name], // 자동 완성 힌트 설정
        ),
        SizedBox(height: 20),
        ElevatedButton(
          onPressed: () {
            // 버튼 클릭 시 입력된 텍스트 출력
            print('Submitted Text: ${_controller.text}');
          },
          child: Text('Submit'),
        ),
      ],
    );
  }
}

 

 

 

 

반응형