How to read a cookie in the browser with Dart?

最后都变了- 提交于 2020-06-28 05:08:37

问题


Question looks simple but I couldn't find in the docs how to read a cookie with Dart on client side without 3-rd party libs.

How can I do it?


回答1:


In the dart:html library you can use document.cookie. This will return a String of all the cookies on the client. Each cookie is separated with a semi-colon and the key value pairs are separated with a "=". Example;

"foo=bar; otherFoo=otherBar"

So it's up to you to split the String accordingly into a data type that you want to work with.

Also see: Document.cookie - Web APIs | MDN




回答2:


I am using documnet.cookie and this class to maintain the cookies.

import 'dart:html';

class CookieManager {

  static addToCookie(String key, String value) {
    document.cookie = "$key=$value;";
  }

  static String getCookie(String key) {

    String cookies = document.cookie;
    List<String> listValues = cookies.isNotEmpty ? cookies.split(";") : List();
    String matchVal = "";
    for (int i = 0; i < listValues.length; i++) {
      List<String> map = listValues[i].split("=");
      String _key = map[0].trim();
      String _val = map[1].trim();
      if (key == _key) {
        matchVal = _val;
        break;
      }
    }
    return matchVal;
  }
}


来源:https://stackoverflow.com/questions/42565211/how-to-read-a-cookie-in-the-browser-with-dart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!