问题
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