set function

void set(
  1. String key,
  2. String value, {
  3. DateTime? expires,
  4. Duration? maxAge,
  5. String? path,
  6. String? domain,
  7. bool? secure,
})

Set a cookie with name key and value.

If the cookie already exists, it gets overwritten.

maxAge is added as a convenience, but always converted to expires. If both maxAge and expires are provided, then maxAge will overwrite expires (this follows the cookie spec).

Implementation

void set(
  String key,
  String value, {
  DateTime? expires,
  Duration? maxAge,
  String? path,
  String? domain,
  bool? secure,
}) {
  if (maxAge != null) expires = DateTime.now().add(maxAge);

  var cookie = ([
    Uri.encodeComponent(key),
    '=',
    Uri.encodeComponent(value),
    expires != null
        ? '; expires=' + formatDate(expires)
        : '', // use expires attribute, max-age is not supported by IE
    path != null ? '; path=' + path : '',
    domain != null ? '; domain=' + domain : '',
    secure != null && secure == true ? '; secure' : ''
  ].join(''));
  document.cookie = cookie;
}