【发布时间】:2019-10-17 15:22:06
【问题描述】:
我喜欢检查我的后端数据库中是否已经存在电子邮件。因此,我尝试使用在异步调用返回后应该更改的状态变量。我找到了以下包含已接受答案的线程。
Flutter - Async Validator of TextFormField
Flutter firebase validation of form field inputs
我尝试了这些答案以及一些变体,但它仍然对我不起作用。我只是模拟后端调用。打印设置 _emailExist 为 true,但我没有看到任何错误。如果我单击该按钮两次,则错误消息将正确显示。
import 'package:flutter/material.dart';
class LoginPage extends StatefulWidget {
LoginPage({Key key}) : super(key: key);
@override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final GlobalKey<FormState> _loginFormKey = GlobalKey<FormState>();
bool _emailExist = false;
@override
initState() {
super.initState();
}
checkEmail(String name) {
// Simulare async call
Future.delayed(Duration(seconds: 2)).then((val) {
setState(() {
_emailExist = true;
});
print(_emailExist);
});
return _emailExist;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Test"),
),
body: Container(
child: SingleChildScrollView(
child: Form(
key: _loginFormKey,
child: Column(
children: <Widget>[
TextFormField(
validator: (value) =>
checkEmail(value) ? "Email already taken" : null,
),
RaisedButton(
child: Text("Login"),
onPressed: () {
if (_loginFormKey.currentState.validate()) {}
},
)
],
),
))));
}
}
【问题讨论】: