skip to Main Content

I want to make a post request which require a model class and a query parameter.I want to pass a query parameter for the email after I have also passed the model class. I am coming from Java background and in Java, you can just use @Query keyword then pass the name of the key for it. I want to achieve the same thing using flutter.
This is how the backend is configured.

PostMapping("/account/create")
    public ResponseEntity<SignUpResponse> createAccount(@RequestBody BankAccountDto bankAccountDto, @RequestParam("email") String email) throws DataNotFoundException, DataNotAcceptableException, DataAlreadyExistException, DataNotFoundException, DataNotAcceptableException, DataAlreadyExistException {
        return bankAccountService.createAccount(bankAccountDto,email);

This is what I tried

static Future<Response?> postData(String endpoint, dynamic body) async {
    var url = Uri.parse(baseUrl + endpoint);
    Map<String, String> header = <String, String>{
      'Authorization': 'Bearer',
      'content-type': 'application/json; charset=UTF-8',
      'Accept': 'application/json'
    };
    try {
      Response response =
          await post(url, body: json.encode(body), headers: header);
      print("The post response returns ${response.body}");
      return response;
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

2

Answers


  1. If you want to add a query parameter just add it to the URL

    var query = "?email=$email";
    var url = Uri.parse(baseUrl + endpoint + query);
    

    If you want to add email to the body, just do something like this

    Map bodyMap = jsonEncode(body);
    bodyMap["email"] = email;
    Response response =
              await post(url, body: bodyMap, headers: header);
    
    Login or Signup to reply.
  2. Try to do this way, it alot cleaner in my opinion

    static Future<Response?> postData(String endpoint, dynamic body) async {
        //var url = Uri.parse(baseUrl + endpoint);
        Map<String, String> header = <String, String>{
          'Authorization': 'Bearer',
          'content-type': 'application/json; charset=UTF-8',
          'Accept': 'application/json'
        };
        try {
          final String authority = "exemple.com";
          // Here your api endpoint
          final String path = "/api/account/create";
          final queryParameters = {"email": "your_email_here"};
    
          final uri = Uri.https(authority, path, queryParameters);
    
          Response response = await post(uri, body: json.encode(body), headers: header);
          print("The post response returns ${response.body}");
          return response;
        } catch (e) {
          print(e.toString());
          return null;
        }
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search