Skip to content

Instantly share code, notes, and snippets.

@nilsmagnus
Last active November 19, 2022 10:52
Show Gist options
  • Save nilsmagnus/2cb8c52f2ef6e7c34f20ff45cee1e786 to your computer and use it in GitHub Desktop.
Save nilsmagnus/2cb8c52f2ef6e7c34f20ff45cee1e786 to your computer and use it in GitHub Desktop.
Post form-data with flutter/dart
import 'package:http/http.dart'; // http library, http:0.13.0
import 'dart:developer'; // logging locally
String? get baseUrl => "http://localhost:8081"
Future<Response> postForm(String path, Map<String, String> body, {Map<String, String>? customHeaders}) async {
final headers = commonHeaders()
..addAll(customHeaders ?? {})
..addAll({"Content-Type": "application/x-www-form-urlencoded"});
log("POST $baseUrl$path with body $body and headers $headers", name: "http_service");
final response = httpClient.post(
Uri.parse("$baseUrl$path"),
body: body.entries.map((e) => "${e.key}=${e.value}").join(),
headers: headers,
);
response.then((value) => log("POST RESPONSE: ${value.body}", name: "http_service local"));
return response;
}
@rekire
Copy link

rekire commented Nov 6, 2022

I think the mapping is incorrect and should be: entries.map((e) => '${e.key}=${Uri.encodeComponent(e.value)}').join('&')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment