【问题标题】:Navigate to next page after API post response success?API 发布响应成功后导航到下一页?
【发布时间】:2021-03-15 08:07:20
【问题描述】:

我正在尝试映射这些数据,以便我可以在颤动中导航到下一个屏幕,但我不知道是否 我对这段代码是正确的

向服务器发送数据

Future login(String email, String password) async {
  String myUrl = Uri.encodeFull('http://192.168.1.00:8000/api/login');
  http.post(myUrl, body: {
    "email": email,
    "password": password,
  }).then((response) {
    print('Response status : ${response.statusCode}');
    print('Response body : ${response.body}');

    Map mapValue = json.decode(response.body);
    print('Token value : ${mapValue.values.toString()}');

    Map<String, dynamic> data = json.decode(response.body);
    // return data;
    print('This, ${data['email']}');
    print('let, ${data['password']}');
  });
}

按下按钮后,我想移动到下一个屏幕

我的按钮

child: RaisedButton(
    textColor: Colors.white,
    color: Colors.blue,
    child: Text('Login'),
    onPressed: () async {
    await login(emailController.text, passwordController.text)
    .then((value) {
    if (value['data']) {
    Navigator.push(context,
    MaterialPageRoute(builder: (context) => NewPage()));
    } else {
    print('failed');
    }
   });
  print(emailController.text);
  print(passwordController.text);
  },
))

【问题讨论】:

    标签: json api flutter postman


    【解决方案1】:

    您可以使用响应状态码来检查数据是否成功发送并重定向到下一页

        Future login(String email, String password) async {
          String myUrl = Uri.encodeFull('http://192.168.1.00:8000/api/login');
          http.post(myUrl, body: {
            "email": email,
            "password": password,
          }).then((response) {
            print('Response status : ${response.statusCode}');
            print('Response body : ${response.body}');
        
            Map mapValue = json.decode(response.body);
            print('Token value : ${mapValue.values.toString()}');
        
            Map<String, dynamic> data = json.decode(response.body);
            // return data;
            print('This, ${data['email']}');
            print('let, ${data['password']}');
            if(response.statusCode == 200){
            //if you want replace current page with the next one
            Navigator.pushReplace(context,MaterialPageRoute(builder: (context) => NextPage()));
            }else{
            scaffoldKey.currentState
              .showSnackBar(SnackBar(content: Text("Something went wrong!!!")));}
          });
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-02
      • 2021-07-20
      • 2021-11-15
      • 2021-03-24
      • 2020-05-20
      • 1970-01-01
      相关资源
      最近更新 更多