如标题中所写,我想知道是否有一种方法可以在用户执行滑动手势弹出当前路线后验证
Form
。
我期望当用户执行滑动时,在某个时刻(比方说在动画的一半),验证
Form
的回调被调用,并且我可以显示一个弹出窗口来通知用户。
当从 AppBar 或物理按钮执行弹出操作时,我已经设法调用验证回调,但我还需要滑动手势,并且使用
GestureDetector
小部件并不是我真正想要的,因为它会删除系统动画。
如果我正确理解了你的问题,这就是解决方案。
class _FormPageState extends State<FormPage> {
final GlobalKey<FormState> _formKey = GlobalKey();
bool get canSubmit => _formKey.currentState?.validate() ?? true;
void submitForm() {
if (canSubmit) {
Navigator.pop(context);
}
}
@override
Widget build(BuildContext context) {
return PopScope(
canPop: false,
onPopInvokedWithResult: (didPop, result) {
if (didPop) return;
submitForm();
},
child: Scaffold(
appBar: AppBar(
title: const Text('Form'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextFormField(
decoration: const InputDecoration(hintText: 'Full name'),
validator: (value) =>
value?.trim().isEmpty ?? true ? 'Provide a name' : null,
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: submitForm,
child: const Text('Submit'),
),
],
),
),
),
),
);
}
}