Jaimin Bhikadiya
Jaimin Bhikadiya

Reputation: 51

How to send data through API in Flutter?

When I try to login (email and password parameter) through APIs, data passes in row format, but I want to post data in form format. Because of this problem, when I pass data it does not accept parameter value and shows null and gives error. So, how can I solve this problem?

> This _loginUser() method In call on login button click.


_loginUser(context) async {
    Map<String, dynamic> loginBodyResponse = {
      "email": _emailController.text,
      "password": _passswordController.text,
    };
    try {
      setState(() {
        _isLoading = true;
      });
> APIs call
      Map loginResponse = await NetworkHttp.postHttpMethod(
          '${AppConstants.apiEndPoint}${AppConstants.loginApi}',
          loginBodyResponse);

          print('email:' + _emailController.text);
          print('Password:' + _passswordController.text);
          print(loginBodyResponse);

      print('===================Login Response=========================');
      print(loginResponse['body']);

      print(loginResponse['body']['login']);

      print("---------------------------");
      if (loginResponse['body']['status'] != "success") {
        setState(() {
          _isLoading = false;
        });
        String errormessage = loginResponse['body']['msg'];
        print("---------------------------");
        print(errormessage);

        ErrorDialog.showErrorDialog(context, errormessage, "Error");
      } else {
        print("Login Successfully");
        print("============================================");
        setState(() {
          _isLoading = false;
        });
        NavigatorHelper.verifyOtpScreen(context);
      }
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      ErrorDialog.showErrorDialog(context, e.toString(), "Error");
      print('error while login $e');
    }
  }

NetworkHttp class which I used in above mention code. when I try to login it shows null parameter in console

class NetworkHttp {
  static Future<Map<String, String>> _getHeaders() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    final String token = prefs.getString('token');
    if (token != null) {
      return {
        'Content-type': 'application/json',
        'Accept': 'application/json',
        'AccessToken': '$token',
      };
    } else {
      return {
        'Content-type': 'application/json',
        'Accept': 'aapilcation/json',
      };
    }
  }

static Future<Map<String, dynamic>> postHttpMethod(String url, body) async {
    print('url');
    print(url);
    print('body');
    print(body);
    Map headers = await _getHeaders();
    print('headers');
    print(headers);
    http.Response response = await http.post(
      url,
      headers: headers,
      body: json.encode(body),
    );
    Map<String, dynamic> responseJson = {
      'body': json.decode(response.body),
      'headers': response.headers
    };
    return responseJson;
  }

Upvotes: 0

Views: 4699

Answers (2)

Vicky Salunkhe
Vicky Salunkhe

Reputation: 10965

With your post request just pass your parameters like this

your post request should look something like below.

response = await http.post("your_api_url",
                           body:{"email" : "value",
                                 "password" : "value"});

Upvotes: 0

Yogesh Sharma
Yogesh Sharma

Reputation: 74

Just add headers with the json_data .

Future<login> requestLogin(String username, String password , String device_id) async {
      Map<String, String> headers = {"Content-type": "application/x-www-form-urlencoded"};
      var json_body = { 'email' : username , 'password': password ,'device_id': device_id};

      if(token != null){
        headers.addAll({"Authorization" : "Bearer "+token});
      }
      //  make POST request
      final response = await http.post(baseUrl+ "/login", headers: headers, body: json_body);
      print(response.body);
      if (response.statusCode == 200) {
        // If server returns an OK response, parse the JSON.
        // return Post.fromJson(json.decode(response.body));
        print(response.body);
        return login.fromJson(json.decode(response.body));
      } else {
        // If that response was not OK, throw an error.
        throw Exception(response.body);
      }
    }

Upvotes: 1

Related Questions