Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Yes Dart has support for sessions which are more or less like in PHP.</p> <p>Let's write a simple program that randomizes a fruit between apples and bananas and saves the choice to the session.</p> <pre class="lang-dart prettyprint-override"><code>import 'dart:io'; import 'dart:math'; // A method that returns "apple" or "banana" randomly. String getRandomFruit() =&gt; 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) =&gt; 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); } </code></pre> <p>Now when you run the code and go to <code>http://localhost</code>, every time you see the same fruit as long as the session stays open, because we save the fruit to the session.</p> <p>Notes:</p> <ul> <li>The <a href="http://api.dartlang.org/docs/bleeding_edge/dart_io/HttpRequest.html" rel="noreferrer"><code>HttpRequest</code></a> class has this method <a href="http://api.dartlang.org/docs/bleeding_edge/dart_io/HttpRequest.html#session" rel="noreferrer"><code>session()</code></a> which initializes (or returns) the <a href="http://api.dartlang.org/docs/bleeding_edge/dart_io/HttpSession.html" rel="noreferrer"><code>HttpSession</code></a> instance.</li> <li>The <a href="http://api.dartlang.org/docs/bleeding_edge/dart_io/HttpSession.html" rel="noreferrer"><code>HttpSession</code></a> has a property called <code>data</code>, but you might want to initialize it first to be an empty <code>{}</code>.</li> </ul>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload