🔖 หมวดบทเรียน: การรับข้อมูลจากผู้ใช้ผ่าน TextField และแบบฟอร์ม
📌 เหมาะสำหรับ: ผู้ที่ต้องการสร้างหน้ากรอกข้อมูล เช่น ฟอร์มสมัครสมาชิก ฟอร์มติดต่อ
🎯 เป้าหมาย: เรียนรู้การใช้
TextField
,Form
,TextEditingController
และการตรวจสอบข้อมูล (validation)
🧭 เกริ่นนำ
แอปพลิเคชันที่มีการกรอกข้อมูล เช่น สมัครสมาชิก ค้นหา หรือส่งข้อความ มักใช้ TextField
เป็นหลัก Flutter มี Form
ที่ช่วยให้เราจัดการหลาย TextField
พร้อมการตรวจสอบข้อมูล (validation) อย่างมีประสิทธิภาพ ในบทนี้เราจะทดลองสร้างฟอร์มอย่างง่ายที่มีการตรวจสอบช่องว่าง
✏️ การใช้งาน TextField
TextField(
decoration: InputDecoration(
labelText: 'ชื่อผู้ใช้',
border: OutlineInputBorder(),
),
)
🔧 การควบคุมค่า TextField ด้วย Controller
final controller = TextEditingController();
TextField(
controller: controller,
)
// อ่านค่าเมื่อกดปุ่ม
print(controller.text);
📋 การใช้งาน Form และการตรวจสอบข้อมูล
final _formKey = GlobalKey<FormState>();
Form(
key: _formKey,
child: TextFormField(
validator: (value) {
if (value == null || value.isEmpty) {
return 'กรุณากรอกข้อมูล';
}
return null;
},
),
)
เรียกตรวจสอบก่อนส่งข้อมูล:
if (_formKey.currentState!.validate()) {
// ดำเนินการส่งข้อมูล
}
🧪 ตัวอย่างฟอร์มพร้อมตรวจสอบ
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: FormPage());
}
}
class FormPage extends StatefulWidget {
@override
_FormPageState createState() => _FormPageState();
}
class _FormPageState extends State<FormPage> {
final _formKey = GlobalKey<FormState>();
final nameController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("ฟอร์มตัวอย่าง")),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
controller: nameController,
decoration: InputDecoration(labelText: "ชื่อผู้ใช้"),
validator: (value) {
if (value == null || value.isEmpty) {
return 'กรุณากรอกชื่อ';
}
return null;
},
),
SizedBox(height: 20),
ElevatedButton(
child: Text("ส่งข้อมูล"),
onPressed: () {
if (_formKey.currentState!.validate()) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("ข้อมูลที่ส่ง: \${nameController.text}")),
);
}
},
),
],
),
),
),
);
}
}
✅ สรุป
TextField
ใช้รับข้อมูลจากผู้ใช้แบบอิสระTextEditingController
ช่วยควบคุมค่าใน TextFieldForm
และTextFormField
เหมาะสำหรับแบบฟอร์มที่มีหลายช่องและต้องการตรวจสอบข้อมูล
ในบทถัดไป เราจะเรียนรู้การใช้งาน ListView
และ ListTile
สำหรับแสดงรายการแบบเลื่อน