passing parameter/input data to custom elements in DART

Issue

I created a custom element, and want to send data / parameters to it:

my element code is:

   class SaveBtn extends HtmlElement  {
   static final tag = 'save-button';
   factory SaveBtn()=>new Element.tag(tag); 

  SaveBtn.created() : super.created() {
  //  Create a Shadow Root
  var shadow = this.createShadowRoot();
 // Create a standard element and set it's attributes.
 var btn = new ButtonElement();
 ...
 btn.text= this.getAttribute('data-name');


 shadow.nodes.add(btn);

    Element launchElement(){ 
     return (shadow); 
    }

  }  
 }

The below code in the html file worked perfectly:

<save-button data-name='save orders'></save-button>

but what if I want to use the below code, what shall I adjust in my custom element code?

new SaveBtn('save orders')

Solution

name is an optional argument. When you pass a value it is used for the text attribute of the button.
I pass it just to a field (name) in the elements class and set it to the the button in attached.
When you use data-xxx attributes you can use the dataset getter.
I also changed the other code a bit. I think attached is a better place to access attributes because then the element is already upgraded properly.

class SaveBtn extends HtmlElement {
  static final tag = 'save-button';

  factory SaveBtn([String name]) => (new Element.tag(tag) as SaveBtn)..name = name;

  ButtonElement innerButton;
  ShadowRoot shadow;

  SaveBtn.created() : super.created() {
    //  Create a Shadow Root
    var shadow = this.createShadowRoot();
    // Create a standard element and set it's attributes.
    innerButton = new ButtonElement();
    shadow.nodes.add(innerButton);
  }

  String name;

  @override
  void attached() {
    super.attached();
    innerButton.text = name != null ? name : this.dataset['name'];
  }
}
SaveBtn({String name, String width}) => (new Element.tag(tag) as SaveBtn)
    ..name = name
    ..style.width=width;

Below a solution proved to work.

factory SaveBtn() => new Element.tag(tag)
  String name, width;

  @override
  void attached() {
    super.attached();
    innerButton.text = name != null ? name : this.dataset['name']
    ..style.width=width;
  }

call the item as:

var btn = new SaveBtn()..name='save'..width='100%';

Answered By – Günter Zöchbauer

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *