Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dio dart/Flutter get and set cookie

I would like to do a set cookies, do a get request and after get the cookies. In python it will be this:

> import requests cookies = {'status': 'working','color':'blue'}
> response = session.get('https://google.com/', cookies=cookies)
> print(session.cookies.get_dict())

Do you know how to flutter it? I tried something like this but it doesn't seem to have a cookie in the response and the cookie doesn't seem to be sent

  Map<String, String> headers = {
      "status":"working",
      "color":"blue"   
    };
    final BaseOptions dioBaseOptions = BaseOptions(
    baseUrl: 'https://google.com',
    headers: {
      'Cookie': headers,
    },
    );
     dio = Dio(dioBaseOptions);
  var cookieJar=CookieJar();
  dio.interceptors.add(CookieManager(cookieJar));
var response = await dio.get('https://google.com/');
like image 559
thibd Avatar asked Sep 16 '25 04:09

thibd


1 Answers

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 on front
  • in my case add "'Access-Control-Allow-Credentials', true" to your header on server, I use Dart on back-end (Alfred framework)
  • check whether origin from your server match with your host:port on front

Your browser will do the job and resend automatically your cookies.

you can define a specific port when launching the app with this command - "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. (withCredentials option is available only on web unfortunately)

If you want to use default http class

you just have to make your own onResponse/onRequest function

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 {
      options.headers['cookie'] = await localData.read('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;
like image 63
bk3 Avatar answered Sep 17 '25 18:09

bk3