0

I've been fairly new to flutter. I was tasked to send the email, name, and password for a signup link given to me. The response on postman response when sending request

The reference PHP code for signup 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);
        }
    });

The flutter code for sending data is

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()
            )
          ),

      ],
    ),
  )));
}
}

When sending responses from the app my requests are not going through and when printing the response i am getting a default response that says that i am not sending any requests.

1
  • I just copy pasted your code and tried it. It is working correctly. Commented Mar 26, 2020 at 10:29

1 Answer 1

2

Try specifying the headers attribute in the http.post method. Here is an example snippet.

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

Finally Deserialize in to a Class object.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your reply. I tried using your headers but I still get the same error: {error: true, message: Required field(s) name, email, password is missing or empty}. Can you please elaborate on how to deserialize into a class object.
It's weird. I see in the PHP code you retrieved the variables. Try printing them through the PHP code. Make sure you type name, email, pasword before you send. For that try adding an if condition in userRegistration code to make sure the values are not null. If the flutter side is correct, then try debugging on the PHP side. On the PHP side try using alternate methods to retrieve post data params.
For serialization/deserialization you can look here: stackoverflow.com/questions/60903044/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.