Depending if you use flutter web or mobile there different ways to get cookies
for flutter web you just have to:
- set credentials to true
- check whether origin from your server match with your host:port on front
you can define a specific port when launching the app
"flutter run -d chrome --web-port 5555"
but for mobile you have to make some tricks
I use Dio package to easily define an onResponse/onRequest function and a conditional import to avoid compilation fail. (withCredential option is available only on web unfortunately.
NetworkConfig.dart
import 'package:dio/dio.dart';
import '../../../constants/url_paths.dart';
import 'get_net_config.dart'
if (dart.library.io) 'mobile_net_config.dart'
if (dart.library.html) 'web_net_config.dart';
class NetworkConfig {
final _client = getClient()
..options = BaseOptions(
baseUrl: url,
connectTimeout: const Duration(seconds: 5),
receiveTimeout: const Duration(seconds: 6),
);
Dio get client => _client;
final Map<String, String> headers = <String, String>{
'Content-Type': 'application/json'
};
}
I use another class to do my get, post... which extends NetworkConfig
get_network_config.dart
import 'package:dio/dio.dart';
Dio getClient() => throw UnsupportedError('[Platform ERROR] Network client');
web_network_config.dart
import 'package:dio/browser.dart';
import 'package:dio/dio.dart';
Dio getClient() =>
Dio()..httpClientAdapter = BrowserHttpClientAdapter(withCredentials: true);
mobile_network_config.dart
import 'dart:io';
import 'package:<projet_name>/data/data.dart';
import 'package:dio/dio.dart';
// CLIENT
Dio getClient() => Dio()
..interceptors.add(InterceptorsWrapper(
onRequest: (options, handler) async {
final cookie = await localData.read('cookie');
options.headers['cookie'] = cookie;
return handler.next(options);
},
onResponse: (response, handler) {
response.headers.forEach((name, values) async {
if (name == HttpHeaders.setCookieHeader) {
final cookieMap = <String, String>{};
for (var c in values) {
var key = '';
var value = '';
key = c.substring(0, c.indexOf('='));
value = c.substring(key.length + 1, c.indexOf(';'));
cookieMap[key] = value;
}
var cookiesFormatted = '';
cookieMap
.forEach((key, value) => cookiesFormatted += '$key=$value; ');
await localData.write('cookie', cookiesFormatted);
return;
}
});
return handler.next(response);
},
));
localData is my wrapper for flutter_secure_storage (to persiste cookies locally)
if you use the default Client() class you can also set credentials like this
import 'package:http/http.dart';
Client getClient() => BrowserClient()..withCredentials = true;