Does Dart support PHP like $_SESSION (sessions)?

2019-07-11 20:41发布

问题:

Does server side Dart support sessions like in PHP:

<?php

session_start();

$_SESSION['fruit'] = 'apple';

The data is kept upon page loads.

回答1:

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:

  • The HttpRequest class has this method session() which initializes (or returns) the HttpSession instance.
  • The HttpSession has a property called data, but you might want to initialize it first to be an empty {}.


标签: dart