Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dynamically add a stylesheet using Dart?

I know in Javascript how to dynamically add a stylesheet. This can be done using the following code:

var sheet = document.createElement('style');

But when I try the same using Dart (https://www.dartlang.org/), like this:

CssStyleSheet sheet = document.createElement('style');

Then the Dart-editor tells me "A value of type Element cannot be assigned to a variable of type CssStyleSheet".

I also tried it like this:

CssStyleSheet styleSheet = new CssStyleSheet();

But that gives me the warning "The class CssStyleSheet does not have a default constructor"

And this:

CssStyleSheet sheet = DomImplementation.createCssStyleSheet('mySheet', '');

Gives met "Instance member 'createCssStyleSheet' cannot be accessed using static access".


So my question is: how do I create a CssStyleSheet in Dart, such that I can use methods like insertRule(rule, index) and deleteRule(index)?

Kind regards,
Hendrik

like image 511
Hendrik Jan Avatar asked May 07 '14 17:05

Hendrik Jan


3 Answers

The answer of Günter Zöchbauer helped me find a solution (see my comment on his answer).
This works:

import 'dart:html';

main () {
  // create a stylesheet element
  StyleElement styleElement = new StyleElement();
  document.head.append(styleElement);
  // use the styleSheet from that
  CssStyleSheet sheet = styleElement.sheet;

  final rule = 'div { border: 1px solid red; }';
  sheet.insertRule(rule, 0);
}
like image 123
Hendrik Jan Avatar answered Nov 07 '22 03:11

Hendrik Jan


I tried it and it worked for me:

import 'dart:html' as dom;

main () {
  dom.document.head.append(new dom.StyleElement());
  final styleSheet = dom.document.styleSheets[0] as dom.CssStyleSheet;
  final rule = 'div { color: blue; }';
  styleSheet.insertRule(rule, 0);
}
like image 45
Günter Zöchbauer Avatar answered Nov 07 '22 03:11

Günter Zöchbauer


For anyone who needs to add an external stylesheet, this is how you do it.

LinkElement link = document.head.append(LinkElement());
link.type = "text/css";
link.rel = "stylesheet";
link.href = "/site.css";
like image 34
markt Avatar answered Nov 07 '22 05:11

markt