Does server side Dart support sessions like in PHP:
<?php
session_start();
$_SESSION['fruit'] = 'apple';
The data is kept upon page loads.
Does server side Dart support sessions like in PHP:
<?php
session_start();
$_SESSION['fruit'] = 'apple';
The data is kept upon page loads.
Yes Dart has support for sessions which are more or less like in PHP.
Let's write a simple program that randomizes a fruit between apples and bananas and saves the choice to the session.
import 'dart:io';
import 'dart:math';
// A method that returns "apple" or "banana" randomly.
String getRandomFruit() => new Random().nextBool() ? 'apple' : 'banana';
main() {
var server = new HttpServer();
server.defaultRequestHandler = (HttpRequest req, HttpResponse res) {
// Initialize session with an empty {} object as data.
var session = req.session((s) => s.data = {});
// Save fruit to session if there is nothing in there.
if (session.data['fruit'] == null)
session.data['fruit'] = getRandomFruit();
// Retrieve fruit from the session.
var fruit = session.data['fruit'];
res.outputStream.writeString("Your fruit: $fruit", Encoding.UTF_8);
res.outputStream.close();
};
server.listen('127.0.0.1', 80);
}
Now when you run the code and go to http://localhost
, every time you see the same fruit as long as the session stays open, because we save the fruit to the session.
Notes:
HttpRequest
class has this method session()
which initializes (or returns) the HttpSession
instance.HttpSession
has a property called data
, but you might want to initialize it first to be an empty {}
.