按下登录按钮时,我想显示一个toast
,以成功或“未找到”消息显示用户详细信息。
new RaisedButton(
onPressed: () {
Future<User> user = _sendToServer();
if (user != null) {
Toast.show("You have logged as ${user.toString()}", context,
duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
} else {
Toast.show("Not found", context,
duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
}
},
child: new Text('log in'),
),
我知道我收到了正确的回复,但无法使用吐司显示它。
Future<User> _sendToServer() async {
DatabaseHelper helper = DatabaseHelper.instance;
if (_key.currentState.validate()) {
// No any error in validation
_key.currentState.save();
User user = await helper.getLogin(email, password);
print("login user ${user.email}");
return user;
} else {
// validation error
setState(() {
_validate = true;
});
return null;
}
}
答案 0 :(得分:0)
您应将onPressed
设为异步,并在等待状态下调用函数或将其用作承诺。
对于exa-
yourFunctiomWithFuture().then((value) {
// Run code here
}, onError: (error) {
print(error);
});
答案 1 :(得分:0)
RaisedButton(
onPressed: () async{ // mark it async
User user = await _sendToServer(); // await to get user
if (user != null) {
Toast.show("You have logged as ${user.toString()}", context,
duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
} else {
Toast.show("Not found", context,
duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
}
},
child: new Text('log in'),
)