Want to make an http request using cookies on flutter? Here’s an example of how to grab a session cookie and return it on subsequent requests. You could easily adapt it to return multiple cookies. Make a Session class and route all your GETs and POSTs through it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | class Session { Map<String, String> headers = {}; Future<Map> get(String url) async { http.Response response = await http.get(url, headers: headers); updateCookie(response); return json.decode(response.body); } Future<Map> post(String url, dynamic data) async { http.Response response = await http.post(url, body: data, headers: headers); updateCookie(response); return json.decode(response.body); } void updateCookie(http.Response response) { String rawCookie = response.headers['set-cookie']; if (rawCookie != null) { int index = rawCookie.indexOf(';'); headers['cookie'] = (index == -1) ? rawCookie : rawCookie.substring(0, index); } } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.