You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter:如何通过ElevatedButton的onPressed调用FutureBuilder实现登录验证?

Flutter 点击按钮触发登录验证(基于FutureBuilder实现)

需求:在Flutter中通过点击按钮的onPressed回调,调用FutureBuilder完成登录验证逻辑。


登录按钮实现

以下是触发登录验证的ElevatedButton代码:

Widget _buttonLogin(){
    return Padding(
      padding: const EdgeInsets.only(right:50.0, left: 50.0),
      child: ElevatedButton(
        onPressed: () {
          _validarLogin();
        },
        child: Text('登录', style: TextStyle(fontSize: 15)),
        style: ElevatedButton.styleFrom(
          primary: Color.fromARGB(255, 9, 107, 152),
          shape: StadiumBorder(),
          padding: EdgeInsets.only(top: 20, right: 20, bottom: 20, left: 20), 
        ),
      ),
    );
  }

登录验证逻辑(结合FutureBuilder)

点击按钮后调用的_validarLogin函数,内部通过FutureBuilder处理API请求的异步状态:

Widget _validarLogin() {
    return FutureBuilder(
      future: loginProvider.validarLogin(usuario.text, password.text),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if(snapshot.hasError) {
          print("进入错误分支");
          return Text(snapshot.error.toString());
        }
        if(snapshot.connectionState == ConnectionState.waiting)
        {
          print("请求等待中");
          return CircularProgressIndicator();
        }
        if(snapshot.data!.isEmpty)
        {
          print("返回数据为空");
          return Text('内容为空');  
        }

        print("snapshot.data中的内容");
        print(snapshot.data);
        return Text('验证通过');
      },
    );
  }

注:原代码中snapshot.data!.size为错误写法,因validarLogin返回String类型,无size属性,改为isEmpty判断返回内容是否为空。


API请求异步函数

FutureBuilder调用的后端验证接口函数:

Future<String> validarLogin(String email, String password) async {
    print("收到的邮箱:");
    print(email);
    print("收到的密码:");
    print(password);
    final value = await http.post(
      Uri.parse('http://serviciosweb.edesesa.com.ar/Usuarios.asmx/ValidarUsuario'),
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },
      body: jsonEncode(<String, String>{
        'mail': email,
        'password': password
      }),
    );
    if (value.statusCode == 200)
    {
      return value.body;
    }
    else
    {
      return value.statusCode.toString();
    }    
  }

内容的提问来源于stack exchange,提问作者Agustin Coronel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 03:16:23