Просто создайте класс API с пользовательским методом для выполнения запросов и сохраните куки в классе.
голая реализация (адаптировано из рабочего кода, все удалено и упрощено):
class MyApi {
String myCookie;
Future<bool> loginUser({@required String username, @required String password}) {
// THIS must be the return point, because we are returning a future!!!
return this.apiRequest(method: 'post', url: 'http://example.com/api/login', params: {'user': username, 'password':password})
.then( (response) {
if (response.statusCode == 200) {
// GET THE COOKIE HERE
myCookie = response.headers.keys.firstWhere((k) => loginResponsehttp.headers[k] == 'cookie', orElse: () => null);
}
}
Future<http.Response> apiRequest({
@required String url,
dynamic params}) async {
// separate in to get an all
if(method == 'get') {
return http.get(url, headers: {'X-Auth': myCookie, 'Content-Type': 'application/json'});
} else if (method == 'post') {
return http.post(url, body: json.encode(params), headers: {'X-Auth': myCookie, "Content-Type": 'application/json'});
} else {
// ERROR!!! throw exception?
throw Exception('Unknown http method: ' + method);
}
}
}