使用 Dart 获取表单输入值

Get form input value with Dart

我正在尝试获取输入元素的值,例如这是简单的形式:

<form id="loginForm">
        <label for="username">Username</label>
        <input required type="text" class="form-control" id="username">
        <label for="password">Passowrd</label>
        <input required type="password"id="password">
    </div>
    <button type="submit">Submit</button>
</form>

with jQuery 我会写:

let value = $("#password").val();

或者我什至可以序列化整个表格,

但在 Dart 中这似乎不起作用:

querySelector('#username').getAttribute('value');

, returns null

我没有使用任何框架,

有什么建议吗?

querySelector 只会 return 一个 HtmlElement. Since you know the result is an InputElement (a TextInputElement)你需要施放它才能获得对 value 属性的访问权限。

(querySelector('#usernames') as InputElement).value

从 Dart 版本 2.2.0 (2019) 开始,上述答案似乎不再有效。现在投射 returns 这个错误:

Uncaught CastError: Instance of 'HtmlElement': type 'HtmlElement' is not a subtype of type 'InputElement'

这是一种无需强制转换即可访问输入字段值的方法:

String value = document.getElementById('username').text;

如果您在使用 querySelector 时将元素提示为 InputElement,您将能够访问它的 value.

  InputElement cityInput = querySelector('#city-input');
  final cityName = cityInput.value;

从 Dart HTML 包版本 0.15.0 开始,这是对我有用的唯一方法

String value= document.querySelector('#movie_id').attributes['value'];

querySelector('xxx').attributes returns 包含值字符串的映射