How do I save a value from a text input box and lo

2019-07-04 06:07发布

问题:

(from the mailing list)

How do I create some sort of text input box that will allow me to save that text and use it later in the code? I am using Dart.

回答1:

Use a combination of InputElements and HTML5 Local Storage. The Storage interface in Dart implements Map, so you can store key/value pairs as strings.

The HTML:

<p>
From local storage: <output id="username-output"></output>
</p>

<label for="username">Username:</label>
<input type="text" name="username" id="username">
<input type="submit" id="save" value="Save">

The Dart:

import 'dart:html';

void main() {
  InputElement username = query('#username');
  InputElement submit = query('#save');
  Element output = query('#username-output');
  Storage localStorage = window.localStorage;

  String savedUsername = localStorage['username'];
  if (savedUsername != null) {
    output.text = savedUsername;
  }

  submit.onClick.listen((Event e) {
    output.text = username.value;
    localStorage['username'] = username.value;
  });
}


标签: dart