사용자 지정 양식 필드
특정 애플리케이션 요구에 맞는 재사용 가능한 사용자 지정 양식 필드를 만들어 모듈성과 사용자 경험을 향상합니다.
사용자 지정 양식 필드은(는) CoddyKit의 무료 Flutter Mobile Development 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Flutter Mobile Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Flutter Mobile Development 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Custom Form Fields?
When building apps, you often need similar input fields across different screens. Think about email inputs, password fields, or phone numbers.
Copying and pasting the same TextFormField code everywhere can lead to messy, hard-to-maintain code. This is where custom form fields come in!
What is a Custom Field?
A custom form field is essentially a Flutter Widget that wraps other input widgets, like TextFormField, and adds specific styling, validation, or behavior.
- Reusability: Define it once, use it everywhere.
- Consistency: Ensures all similar inputs look and behave the same.
- Clean Code: Reduces boilerplate and improves readability.
Basic Custom Field Structure
Let's start with a simple custom text input field. We'll create a StatelessWidget that wraps a TextFormField. This allows us to define its basic look and feel.
import 'package:flutter/material.dart';
class CustomTextInput extends StatelessWidget {
final String hintText;
const CustomTextInput({Key? key, required this.hintText}) : super(key: key);
@override
Widget build(BuildContext context) {
return TextFormField(
decoration: InputDecoration(
hintText: hintText,
border: OutlineInputBorder(),
),
);
}
}
void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Custom Field Demo')),
body: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: CustomTextInput(hintText: 'Enter your name'),
),
),
),
));
}Adding Controllers & Validation
For our custom field to be truly useful, it needs to accept a TextEditingController to manage its value and a FormFieldValidator for validation. We pass these as parameters to our custom widget.
import 'package:flutter/material.dart';
class CustomValidatedInput extends StatelessWidget {
final String hintText;
final TextEditingController controller;
final String? Function(String?)? validator;
const CustomValidatedInput({
Key? key,
required this.hintText,
required this.controller,
this.validator,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return TextFormField(
controller: controller,
decoration: InputDecoration(
hintText: hintText,
border: OutlineInputBorder(),
),
validator: validator,
);
}
}
void main() {
final TextEditingController _nameController = TextEditingController();
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Validated Field Demo')),
body: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
child: CustomValidatedInput(
hintText: 'Enter your name (min 3 chars)',
controller: _nameController,
validator: (value) {
if (value == null || value.length < 3) {
return 'Name must be at least 3 characters.';
}
return null;
},
),
),
),
),
),
));
}A Reusable Email Field
Let's create a specific custom field for email input. It will have a predefined keyboard type and a common email validation pattern. This makes it easy to use consistently.
import 'package:flutter/material.dart';
class CustomEmailField extends StatelessWidget {
final TextEditingController controller;
final String labelText;
const CustomEmailField({
Key? key,
required this.controller,
this.labelText = 'Email',
}) : super(key: key);
@override
Widget build(BuildContext context) {
return TextFormField(
controller: controller,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: labelText,
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.email),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your email.';
}
if (!RegExp(r"^[a-zA-Z0-9.]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
.hasMatch(value)) {
return 'Please enter a valid email.';
}
return null;
},
);
}
}
void main() {
final TextEditingController _emailController = TextEditingController();
final _formKey = GlobalKey<FormState>();
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Custom Email Field Demo')),
body: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
children: [
CustomEmailField(controller: _emailController),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
print('Email: ${_emailController.text}');
}
},
child: Text('Submit'),
),
],
),
),
),
),
),
));
}Generic Custom Text Input
What if you need a custom field that's flexible enough for various text inputs (names, addresses, etc.) but still offers custom styling? You can pass more properties to make it generic.
import 'package:flutter/material.dart';
class GenericCustomTextField extends StatelessWidget {
final TextEditingController controller;
final String labelText;
final TextInputType keyboardType;
final bool obscureText;
final String? Function(String?)? validator;
const GenericCustomTextField({
Key? key,
required this.controller,
required this.labelText,
this.keyboardType = TextInputType.text,
this.obscureText = false,
this.validator,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return TextFormField(
controller: controller,
keyboardType: keyboardType,
obscureText: obscureText,
decoration: InputDecoration(
labelText: labelText,
border: OutlineInputBorder(),
),
validator: validator,
);
}
}
void main() {
final TextEditingController _usernameController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
final _formKey = GlobalKey<FormState>();
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Generic Field Demo')),
body: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
children: [
GenericCustomTextField(
controller: _usernameController,
labelText: 'Username',
validator: (value) => value!.isEmpty ? 'Enter username' : null,
),
SizedBox(height: 20),
GenericCustomTextField(
controller: _passwordController,
labelText: 'Password',
obscureText: true,
validator: (value) => value!.length < 6 ? 'Min 6 chars' : null,
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
print('Username: ${_usernameController.text}');
print('Password: ${_passwordController.text}');
}
},
child: Text('Login'),
),
],
),
),
),
),
),
));
}Adding Interactive Elements
Custom fields can also include interactive elements like suffix icons that change state. A common example is a password field with a toggle to show/hide text.
For this, our custom field needs to be StatefulWidget to manage the visibility state.
Custom Password Field with Toggle
Here's how to build a custom password field that allows users to toggle password visibility. Notice the use of StatefulWidget to manage the internal _obscureText state.
import 'package:flutter/material.dart';
class CustomPasswordField extends StatefulWidget {
final TextEditingController controller;
final String labelText;
const CustomPasswordField({
Key? key,
required this.controller,
this.labelText = 'Password',
}) : super(key: key);
@override
_CustomPasswordFieldState createState() => _CustomPasswordFieldState();
}
class _CustomPasswordFieldState extends State<CustomPasswordField> {
bool _obscureText = true;
@override
Widget build(BuildContext context) {
return TextFormField(
controller: widget.controller,
obscureText: _obscureText,
decoration: InputDecoration(
labelText: widget.labelText,
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.lock),
suffixIcon: IconButton(
icon: Icon(
_obscureText ? Icons.visibility : Icons.visibility_off,
),
onPressed: () {
setState(() {
_obscureText = !_obscureText;
});
},
),
),
validator: (value) {
if (value == null || value.length < 6) {
return 'Password must be at least 6 characters.';
}
return null;
},
);
}
}
void main() {
final TextEditingController _passwordController = TextEditingController();
final _formKey = GlobalKey<FormState>();
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Password Field Demo')),
body: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
children: [
CustomPasswordField(controller: _passwordController),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
print('Password: ${_passwordController.text}');
}
},
child: Text('Submit'),
),
],
),
),
),
),
),
));
}Benefits of Custom Fields
Using custom form fields significantly improves your application's development and maintenance:
- Code DRYness: Don't Repeat Yourself, leading to less code.
- Easier Updates: Change one custom field, and all instances update automatically.
- Better UX: Ensures a consistent and intuitive user experience across your app.
- Simplified Logic: Encapsulates complex validation or UI logic within the field itself.
Quick Check: Custom Fields
Which of the following are primary benefits of creating custom form fields in Flutter?
Recap: Custom Form Fields
You've learned how to create custom form fields in Flutter! By wrapping existing input widgets in your own StatelessWidget or StatefulWidget, you can build reusable, consistent, and maintainable input components.
This approach helps keep your code clean, centralizes design and validation, and drastically improves the user experience by providing a unified interface across your application.
자주 묻는 질문
“사용자 지정 양식 필드” 강의는 무료인가요?
네 — “사용자 지정 양식 필드” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Flutter Mobile Development 강의 전체를 잠금 해제할 수 있습니다. Flutter Mobile Development 강의에는 총 4개의 강의가 포함되어 있습니다.
“사용자 지정 양식 필드”에서 뭘 배우나요?
특정 애플리케이션 요구에 맞는 재사용 가능한 사용자 지정 양식 필드를 만들어 모듈성과 사용자 경험을 향상합니다. 브라우저에서 직접 실행하는 실습 코드로 Flutter Mobile Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Flutter Mobile Development을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Flutter Mobile Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“사용자 지정 양식 필드” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Flutter Mobile Development 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Flutter Mobile Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Form 위젯 및 컨트롤러
- 입력 검증 기법
- 사용자 지정 양식 필드
- 포커스, 키보드, 입력 UX