【问题标题】:Http requests not getting response when using flutter使用颤振时Http请求没有得到响应
【发布时间】:2020-07-06 22:56:59
【问题描述】:

我对 Flutter 还很陌生。我的任务是发送给我的注册链接的电子邮件、姓名和密码。上的回应 postman response when sending request

注册参考PHP代码link

        index.php
    /**
     * User Registration
     * url - /register
     * method - POST
     * params - name, email, password
     */

$app->post('/register', function() use ($app) {
            // check for required params
            verifyRequiredParams(array('name', 'email', 'password'));

        $response = array();

        // reading post params
        $name = $app->request->post('name');
        $email = $app->request->post('email');
        $password = $app->request->post('password');

        // validating email address
        validateEmail($email);

        $db = new DbHandler();
        $res = $db->createUser($name, $email, $password);

        if ($res == USER_CREATED_SUCCESSFULLY) {
            $response["error"] = false;
            $response["message"] = "You are successfully registered";
            echoRespnse(201, $response);
        } else if ($res == USER_CREATE_FAILED) {
            $response["error"] = true;
            $response["message"] = "Oops! An error occurred while registereing";
            echoRespnse(200, $response);
        } else if ($res == USER_ALREADY_EXISTED) {
            $response["error"] = true;
            $response["message"] = "Sorry, this email already existed";
            echoRespnse(200, $response);
        }
    });

发送数据的flutter代码是

import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

import 'newScreen.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
  home: Scaffold(
      appBar: AppBar(title: Text('User Registration Form')),
      body: Center(
        child: RegisterUser()
        )
      )
    );
}
}

class RegisterUser extends StatefulWidget {

RegisterUserState createState() => RegisterUserState();

}

class RegisterUserState extends State {

  // Boolean variable for CircularProgressIndicator.
  bool visible = false ;

  // Getting value from TextField widget.
  final nameController = TextEditingController();
  final emailController = TextEditingController();
  final passwordController = TextEditingController();

Future userRegistration() async{

  // Showing CircularProgressIndicator.
  setState(() {
  visible = true ; 
  });

  // Getting value from Controller
  String name = nameController.text;
  String email = emailController.text;
  String password = passwordController.text;

  // SERVER API URL
  var url = 'http://cafeliant.com/android-login/signupApi.php';

  var headers = {
      'content-type': 'application/json'
    };
  // Store all data with Param Name.
  var data = {'name': name, 'email': email, 'password' : password};

  // Starting Web API Call.
  var response = await http.post(url, body: json.encode(data),);

  // Getting Server response into variable.
  var message = jsonDecode(response.body);
  print(message);

  // If Web call Success than Hide the CircularProgressIndicator.
  if(response.statusCode == 200){
  setState(() {
    visible = false; 
  });
}

  // Showing Alert Dialog with Response JSON Message.
  showDialog(
  context: context,
  builder: (BuildContext context) {
    return AlertDialog(
      title: new Text("message"),
      actions: <Widget>[
        FlatButton(
          child: new Text("OK"),
          onPressed: () {
            Navigator.of(context).push(MaterialPageRoute(builder: (context) => newS(),));
          },
        ),
      ],
    );
  },
  );

}

@override
Widget build(BuildContext context) {
return Scaffold(
  body: SingleChildScrollView(
    child: Center(
    child: Column(
      children: <Widget>[

        Padding(
          padding: const EdgeInsets.all(12.0),
          child: Text('User Registration Form', 
                  style: TextStyle(fontSize: 21))),

        Divider(),          

        Container(
        width: 280,
        padding: EdgeInsets.all(10.0),
        child: TextField(
            controller: nameController,
            autocorrect: true,
            decoration: InputDecoration(hintText: 'Enter Your Name Here'),
          )
        ),

        Container(
        width: 280,
        padding: EdgeInsets.all(10.0),
        child: TextField(
            controller: emailController,
            autocorrect: true,
            decoration: InputDecoration(hintText: 'Enter Your Email Here'),
          )
        ),

        Container(
        width: 280,
        padding: EdgeInsets.all(10.0),
        child: TextField(
            controller: passwordController,
            autocorrect: true,
            obscureText: true,
            decoration: InputDecoration(hintText: 'Enter Your Password Here'),
          )
        ),

        RaisedButton(
          onPressed: userRegistration,
          color: Colors.green,
          textColor: Colors.white,
          padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
          child: Text('Click Here To Register User Online'),
        ),

        Visibility(
          visible: visible, 
          child: Container(
            margin: EdgeInsets.only(bottom: 30),
            child: CircularProgressIndicator()
            )
          ),

      ],
    ),
  )));
}
}

当从应用程序发送响应时,我的请求没有通过,当打印响应时,我得到一个默认响应,表明我没有发送任何请求。

【问题讨论】:

  • 我只是复制粘贴了您的代码并尝试了它。它工作正常。

标签: api http flutter flutter-dependencies flutter-web


【解决方案1】:

尝试在http.post 方法中指定headers 属性。这是一个示例 sn-p。

var response = await http.post(
    url,
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(jsonData),
  );

最后反序列化为 Class 对象。

【讨论】:

  • 感谢您的回复。我尝试使用您的标头,但仍然收到相同的错误:{error: true, message: required field(s) name, email, password is missing or empty}。您能否详细说明如何反序列化为类对象。
  • 这很奇怪。我在 PHP 代码中看到您检索了变量。尝试通过 PHP 代码打印它们。确保在发送前输入姓名、电子邮件、密码。为此,请尝试在 userRegistration 代码中添加 if 条件以确保值不为空。如果flutter端是正确的,那么尝试在PHP端调试。在 PHP 端尝试使用替代方法来检索发布数据参数。
  • 序列化/反序列化可以看这里:stackoverflow.com/questions/60903044/…
猜你喜欢
  • 2012-11-21
  • 2019-09-10
  • 2023-03-23
  • 1970-01-01
  • 2020-10-22
  • 1970-01-01
  • 2020-11-09
  • 2020-02-09
  • 1970-01-01
相关资源
最近更新 更多