fluttercookiesflutter-web

How to get a cookie in Flutter Web from header?


The Flutter Web application send a HTTP REST API POST request and gets back a JSON response and a cookie in the Set-Cookie header as follows.

(Flutter (Channel beta, 1.22.0, on Microsoft Windows)

Set-Cookie header

When the cookie is extracted, the response does not seem find the header value. The call and extraction code is:

var response = await http.post(url, headers: {"Content-Type": "application/json"}, body: jsonEncode(data));

if (response.statusCode == 200) {
  var cookie = response.headers['set-cookie'];
  print('cookie: $cookie');
}

The console result is:

cookie: null

The server side runs on ASPNet.Core 3.1 in a Docker container, however it should not be an issue, since the cookie is there in the header. So, how can I extract it in Flutter Web?

Actually my final goal is to send the cookie back with every other request. But it does not seem to happen automatically in the browser. So it is also a good solution if someone could point out the proper way of handling this scenario.

Any help is appretiated. Thanks.


Solution

  • The question was asked a month ago but my answer might be helpful for someone else. Cookies in Flutter Web are managed by browser - they are automatically added to requests (to Cookie header), if the cookie was set by Set-Cookie previously - more precisely, it works correctly when you do release build. In my case it didn't work during dev builds. My solution:

    On server set headers:

    Access-Control-Allow-Credentials: true
    Access-Control-Allow-Origin: http://localhost:61656
    

    // port number may be different

    In flutter: class member:

    final http.Client _client = http.Client();
    

    // example

    Future<String> getTestString() async {
        if (_client is BrowserClient)
          (_client as BrowserClient).withCredentials = true;
        await _client.get('https://localhost/api/login');
        await _client.get('https://localhost/api/login');
        return 'blah';
      }
    

    http.Client() creates an IOClient if dart:io is available and a BrowserClient if dart:html is available - in Flutter Web dart:html is available. Setting withCredentials to true makes cookies work.

    Run your app:

    flutter run -d chrome --web-port=61656
    

    // the same port number that on server

    Remember that in Flutter Web network requests are made with browser XMLHttpRequest.