FutureBuilder始终返回Future的实例

时间:2020-06-10 14:42:26

标签: flutter dart

我尝试在用户登录或登录失败时显示自定义消息。 我的post api调用未返回任何内容,因此我想基于响应状态代码来了解日志是否正常运行。

我在api中做了类似的事情:

  Future<Response> login(String email, String password) async {
     final http.Response response = await http.post(
     baseUrl + 'auth/login',
     headers: headers,
     body: jsonEncode(<String, dynamic> {
      'email': email,
      'password': password
    }),
);
return response.statusCode == 200 ? Response(statusCode: 200) : Response(message: "Failed to login");}

class Response {
 final String message;
 final int statusCode;

 Response({this.message, this.statusCode});

 factory Response.fromJson(Map<String, dynamic> json) {
  return Response(
    message: json["message"],
 );}}

然后我在FutureBuilder中调用此方法以显示消息:

       FutureBuilder(
         future: lap.login(emailController.text, passwordController.text),
         builder: (BuildContext context, AsyncSnapshot<Response> snapshot) {

           if(snapshot.hasData)
             print(snapshot.data.statusCode);
          return CircularProgressIndicator();
         },);

在我的打印方法中,我什么也不打印,我不明白为什么它不显示我在api方法中返回的状态代码。

有人知道为什么吗?

1 个答案:

答案 0 :(得分:0)

我终于用.then()完成了工作。 仍然不明白为什么第一种方法没有做到,但毕竟它能起作用。

 onPressed: () {
   if(_formKey.currentState.validate()) {
      lap.login(emailController.text, passwordController.text)
      .then((responseMessage) => Scaffold
      .of(context)
      .showSnackBar(SnackBar(content: Text(responseMessage.message))));
   }
},