Instance of Paper elements in dart

2019-02-27 11:03发布

How can I get an instance to the paper-input element below?

HTML file:

<!DOCTYPE html>
<html>
<head>
  <!-- <script src='packages/web_components/platform.js'></script>
       not necessary anymore with Polymer >= 0.14.0 -->
  <script src='packages/web_components/dart_support.js'></script>    
  <link rel='import' href='packages/paper_elements/paper_input.html'>
  <script src='packages/browser/dart.js'></script>
</head>
<body fullbleed unresolved>
  <paper-input id='subject' label='subject'></paper-input>
  <script type='application/dart' src='myscript.dart'></script>
</body>
</html>

myscript.dart:

import 'dart:html';
import 'package:polymer/polymer.dart';
import 'package:paper_elements/paper_input.dart';
export 'package:polymer/init.dart';
PaperInput _subject = querySelector('#subject');    // exception
void main() {
  ...
}

This causes an exception:

Breaking on exception: type 'HtmlElement' is not a subtype of type 'PaperInput'

Casting from HtmlElement to PaperInput does not work. Suggestions have included using shadowRoot.querySelector('#subject'); and other shadowRoot usages, but where does it come from? If I append .shadowRoot.querySelector('paper-input') to the last line of myscript.dart, the element is null. Same result if I use the id instead of tag name. The element itself is top-level to the html body, so it is not in any other shadowRoot.

There is no way to get the contents of the paper-input without it being of the class PaperInput. But there seems no way to cast it.

1条回答
甜甜的少女心
2楼-- · 2019-02-27 11:38

You run into how to implement a main function in polymer apps

When you do it like shown below or inside a Polymer element (attached() after super.attached() or in some click or other event handler (when the element is properly initialized)

main() {
  initPolymer().run(() {
    // code here works most of the time
    Polymer.onReady.then((_) {     
      // some things must wait until onReady callback is called
      // for an example look at the discussion linked below

      PaperInput _subject = querySelector('#subject');
    });
  });
}
查看更多
登录 后发表回答