TextFormField Flutter
การแยก TextFormField มาเป็น State Less Widget และ ส่งค่า กลับไป พร้อม Validate ค่าด้วย FormStateKey
ตัวอย่าง โค้ดครับ
import ‘package:flutter/material.dart’;
class ShowTextFormField extends StatelessWidget {
final String label;
final Function(String?) mySave;
final String? Function(String?)? myValidate;
const ShowTextFormField(
{Key? key,required this.label, required this.mySave, required this.myValidate})
: super(key: key);
@override
Widget build(BuildContext context) {
return TextFormField(
onSaved: mySave,
validator: myValidate,
decoration: InputDecoration(
border: const OutlineInputBorder(),
label: Text(label),
),
);
}
}
import ‘package:flutter/material.dart’;
import ‘package:ungtravel/widgets/show_textformfield.dart’;
class TestWidget extends StatefulWidget {
const TestWidget({Key? key}) : super(key: key);
@override
_TestWidgetState createState() => _TestWidgetState();
}
class _TestWidgetState extends State<TestWidget> {
final formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: newAppBar(),
body: Center(
child: SizedBox(
width: 250,
child: Form(
key: formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ShowTextFormField(
label: ‘Name’,
mySave: myName,
myValidate: myVerlidate,
),
const SizedBox(
height: 16,
),
ShowTextFormField(
label: ‘Surname’,
mySave: mySurname,
myValidate: myVerlidate,
),
const SizedBox(
height: 16,
),
ElevatedButton(
onPressed: () {
if (formKey.currentState!.validate()) {
formKey.currentState!.save();
}
},
child: const Text(‘Save’),
),
],
),
),
),
),
);
}
AppBar newAppBar() {
return AppBar(
title: const Text(‘Test Widget’),
);
}
String? myVerlidate(String? string) {
if (string!.isEmpty) {
return ‘Fill In Blank’;
} else {
return null;
}
}
myName(String? string) {
print(‘Name ==>> $string’);
}
mySurname(String? string) {
print(‘Surname ==>> $string’);
}
}
String? myVerlidate(String? string) {
if (string!.isEmpty) {
return ‘Fill In Blank’;
} else {
return null;
}
}
ผลลัพธ์ครับ
สำหรับใครที่ไม่ได้ หรือมีคำถาม ทิ้งคำถามไว้ได้ที่ https://www.facebook.com/Flutter.Training.by.EWTC หรือ หาวันที่สะดวก สัก 2 วันมาลุย ออนไลด์ กันครับ
รายละเอียด คอร์ส สอน Flutter ตัวต่อตัว แบบ ออนไลด์ เลือกหัวข้อเรียนได้ กับ มาสเตอร์ อึ่งครับ เรียนกัน 9.00–16.00 บันทึ่กวีดีโอไว้ดูภายหลังได้นะ
ดูรายละเอียดที่
https://www.flutterthailand.com
ไม่เข้าใจ อะไร ? โพสถามมาสเตอร์ ได้ หรือ จะโทรที่ 0818595309 ได้ครับ