How print values in dart to browser - dart

The below code is to extract parameter from URL using dart
I am able to print the values in console but i am not able to get how to display the output in console to browser that is html version. Please help
import 'dart:core';
import 'dart:html';
void main() {
var q = '?id=abc&id1=cde&id3=asad';
if(q.contains('?')) {
var a = q.replaceFirst("?"," ");
var c = a.split("&");
print(c);
}

You can add the output to the body element or you add an element like a <div></div> and insert it inside this element.
To use a 'div' element you should add an element in you index.html (or whatever name you have for your HTML page) like
...
<body>
<div id='someDiv'></div>
</body>
in your Dart code you do it like
import 'dart:core';
import 'dart:html';
void main() {
var q = '?id=abc&id1=cde&id3=asad';
if(q.contains('?')) {
var a = q.replaceFirst("?"," ");
var c = a.split("&");
// querySelector('#someDiv').text = '${c}'; // <= you may need some encoding for special characters like <, >, &, ...
var div = querySelector('#someDiv');
c.forEach((e) => div.append(new DivElement()..text = '${e}'));
}

Related

inject Image without removing src attribute

is there a way to inject HTML without filtering the src attribute in Dart (no security needed in context), I've tried setInnerHtml, but it doesn't let src pass it...
here's the div I'm adding html in:
<div id="output">
<!--here goes messages-->
</div>
here's my dart code:
import 'dart:html';
import 'dart:async';
InputElement input = querySelector("#textInput");
var output = querySelector("#output");
var buttonSend = querySelector("#send");
var buttonImg = querySelector("#url");
var buttonVideo = querySelector("#video");
Future<Null> main() async {
//send custom message
buttonSend.onClick.listen((MouseEvent event) async{
addContent(input.value);
});
//send img
buttonImg.onClick.listen((MouseEvent event) async{
addContent(getPrefabImg(input.value));
});
//send video
buttonVideo.onClick.listen((MouseEvent event) async{
addContent(getPrefabVideo(input.value));
});
}
//if user use a prefab img
String getPrefabImg(url) {
return "<img class='prefabImg' src='" + url + "'>";
}
//if user use a prefab video
String getPrefabVideo(url) {
return "<iframe class='prefabVideo'' src='" + url + "' frameborder='0' allowfullscreen></iframe>";
}
//reset input and add content
void addContent(value){
output.setInnerHtml(value + output.innerHtml);
input.value = null;
}
To create and inject HTML into the DOM without a NodeTreeSanitizer, you will need to switch from using HTML Strings to using Dart's Node objects. Picking a couple of functions from your code as an example, you can change them to something like;
ImageElement getPrefabImg(String url) {
return new ImageElement(src: url)..classes.add('prefabImage');
}
void addContent(Node node) {
output.nodes.insert(0, node);
input.value = null;
}
But with your current code you can easily add a NodeTreeSanitizer like so;
void addContent(String value) {
output.insertAdjacentHtml(
'afterBegin', value, treeSanitizer: NodeTreeSanitizer.trusted);
input.value = null;
}

DART custom elements (Vanilla DART without Polymer)

I came through DART custom elements, from dartlang.org site, here and here.
If I understood correctly,this is a vanilla DART custom element, not related to Polymer custom tags.
I wrote the below code,
class CustomElement extends HtmlElement {
factory CustomElement() => new Element.tag('x-custom');
CustomElement.created() : super.created() {
print('CustomElement created!');
}
}
void main() {
document.registerElement('x-custom', CustomElement);
}
and got the "CustomElement created!" statement printed in the console, which means the element had been created!
my question is, what else? how can I use this customs element, and what can I do with it can I write HTML template, if yes, how?
I read this but unfortunately could not how to do same with DART.
any thoughts!
This is also used by Polymer. Polymer is just the combination of Custom Element, HTML Imports, Template, Polymer, Polyfills and some builerplate to connect these parts and provider a nice API.
If you want to reinvent the wheel you can go with CustomElement alone.
Change your main to
void main() {
document.registerElement('x-custom', CustomElement);
var elem = new Element.tag('x-element');
elem.appendText('x-element');
document.body.append(elem);
elem.onClick.listen((e) {
print('clicked');
});
}
and you can react to click events
I was ableto write the below, which had been worked, feel I did it the long way,
I could not use the tag
Not sure if the way I used to callback the elements in the custumElement in the correct way, as I was forced to use .append for all the items, and not sure if there is an easier way to do it.
my index.html file is
pick a color:<input type="color" name="colorname" id="colorname"> the color you selected is: <output id="picked-color"></output> click it !
<div id='my-element'></div>
my index.dart file is:
import 'dart:html';
class CustomElement extends HtmlElement {
factory CustomElement() => new Element.tag('x-custom');
CustomElement.created() : super.created() { }
Element launchElement(Element o1){
o1.onClick.listen((e) => window.alert('the input color is: ${o1.text}'));
print('CustomElement created!');
var output = new Element.html('<div></div>');
var statement = new Element.html('<div></div>');
var bind = new Element.html('<div></div>')
..text='this text will be dynamically replaced by what you are entering down';
var input = new InputElement()
..id ='input'
..type ='text'
..placeholder='enter data here';
input.onInput.listen((e) => bind.text=input.value);
var element = new Element.html('<span>content: </span>')
..style.color='red';
var button = new ButtonElement()
..id = 'awesome'
..classes.add('important')
..onClick.listen((e) => pop(input.value)) // "Hi There!!!")
..text = 'Click Me man!'
..style.color='orange';
statement.innerHtml="<b>I'm an x-custom-with-markup!</b> ";
output.node..add(statement)..add(bind)..add(input)..add(element)..add(button);
return (output);
}
var button1 = new ButtonElement()
..id = 'awesome2'
..text = 'External Click Me man!';
void pop(i){ window.alert("input is: $i"); }
}
void main() {
document.registerElement('x-custom', CustomElement);
var xFoo = new Element.tag('x-custom');
InputElement colorname = querySelector('#colorname');
Element theColor = querySelector('#picked-color');
xFoo = xFoo.launchElement(theColor);
theColor.text = colorname.value;
Element myDiv=querySelector('#my-element');
myDiv.children.add(xFoo);
colorname.onInput.listen((Event e) {
theColor.text = colorname.value;
});
}
Not available now
document.registerElement is deprecated: https://developer.mozilla.org/zh-CN/docs/Web/API/Document/registerElement
window.customElements.define with Dart is blocked by https://github.com/dart-lang/sdk/issues/35829

Dart2js warnings when using ElementList length and []

I am new to Dart. To become familiar with Dart, I created this script. It works fine with the editor and pub serve. But pub serve dart2js logs these two warnings, which I do not understand:
No member named 'length' in class 'ElementList'
No operator '[]' in class ElementList
coloring.dart:
import 'dart:math';
import 'dart:html';
import 'dart:async';
const String CLICK_ME = 'Click me to pause!';
void randomColoring(StreamSubscription subscription) {
final Random random = new Random();
final Element intro = querySelector("#intro");
final ElementList<Element> boxes = querySelectorAll('.box');
final Element info = querySelector("#info");
subscription.onData((eventValue) {
var box = random.nextInt(boxes.length); /// WARNING
var hexCssColor = random.nextInt(0xFFFFFF + 1).toRadixString(16)
.padLeft(6, "0").toUpperCase();
boxes[box].style.background = "#$hexCssColor"; /// WARNING
info.text = eventValue.toString();
print("box: $box - hexCssColor: $hexCssColor - count: $eventValue");
});
var text = intro.text;
intro
..text = CLICK_ME
..onClick.listen((mouseEvent) {
if (subscription.isPaused) {
intro.text = CLICK_ME;
subscription.resume();
} else {
intro.text = text;
subscription.pause();
}
});
}
There is a bug for the [] operator of ElementList https://code.google.com/p/dart/issues/detail?id=19628 (fixed at June 26).
What Dart version are you using?
I wasn't able to find something about length but I guess it's a bug in Dart2JS.
You can report it at http://dartbug.com/new
But maybe the fix for the [] bug applies here as well.

JSON.parse to Map howto (new syntax 0.3.1_r17328)

What's the new syntax for the following please? :
Map mAcctData = JSON.parse(sResponse); // sResponse is Json String
parse (and stringify) has been moved to a top-level function.
import 'dart:json' as JSON; // note the JSON name
main() {
var text = // some text...
var map = JSON.parse(text); // using the JSON name
}
or
import 'dart:json'; // note, no JSON name
main() {
var text = // some text...
var map = parse(text); // calling parse as a top-level function.
}

How do I read console input / stdin in Dart?

How do I read console input from stdin in Dart?
Is there a scanf in Dart?
The readLineSync() method of stdin allows to capture a String from the console:
import 'dart:convert';
import 'dart:io';
void main() {
print('1 + 1 = ...');
var line = stdin.readLineSync(encoding: utf8);
print(line?.trim() == '2' ? 'Yup!' : 'Nope :(');
}
Old version:
import 'dart:io';
main() {
print('1 + 1 = ...');
var line = stdin.readLineSync(encoding: Encoding.getByName('utf-8'));
print(line.trim() == '2' ? 'Yup!' : 'Nope :(');
}
The following should be the most up to date dart code to read input from stdin.
import 'dart:async';
import 'dart:io';
import 'dart:convert';
void main() {
readLine().listen(processLine);
}
Stream<String> readLine() => stdin
.transform(utf8.decoder)
.transform(const LineSplitter());
void processLine(String line) {
print(line);
}
import 'dart:io';
void main(){
stdout.write("Enter your name : ");
var name = stdin.readLineSync();
stdout.write(name);
}
Output
Enter your name : Jay
Jay
By default readLineSync() takes input as string. But If you want integer input then you have to use parse() or tryparse().
With M3 dart classes like StringInputStream are replaced with Stream, try this:
import 'dart:io';
import 'dart:async';
void main() {
print("Please, enter a line \n");
Stream cmdLine = stdin
.transform(new StringDecoder())
.transform(new LineTransformer());
StreamSubscription cmdSubscription = cmdLine.listen(
(line) => print('Entered line: $line '),
onDone: () => print(' finished'),
onError: (e) => /* Error on input. */);
}
As of Dart 2.12, null-safety is enabled, and stdin.readLineSync() now returns a String? instead of a String.
This apparently has been confusing a lot of people. I highly recommend reading https://dart.dev/null-safety/understanding-null-safety to understand what null-safety means.
For stdin.readLineSync() specifically, you can resolve this by checking for null first, which for local variables will automatically promote a String? to a String. Here are some examples:
// Read a line and try to parse it as an integer.
String? line = stdin.readLineSync();
if (line != null) {
int? num = int.tryParse(line); // No more error about `String?`.
if (num != null) {
// Do something with `num`...
}
}
// Read lines from `stdin` until EOF is reached, storing them in a `List<String>`.
var lines = <String>[];
while (true) {
var line = stdin.readLineSync();
if (line == null) {
break;
}
lines.add(line); // No more error about `String?`.
}
// Read a line. If EOF is reached, treat it as an empty string.
String line = stdin.readLineSync() ?? '';
Note that you should not blindly do stdin.readLineSync()!. readLineSync returns a String? for a reason: it returns null when there is no more input. Using the null assertion operator (!) is asking for a runtime exception.
Note that while calling stdin.readLineSync() your isolate/thread will be blocked, no other Future will be completed.
If you want to read a stdin String line asynchronously, avoiding isolate/thread block, this is the way:
import 'dart:async';
import 'dart:convert';
import 'dart:io';
/// [stdin] as a broadcast [Stream] of lines.
Stream<String> _stdinLineStreamBroadcaster = stdin
.transform(utf8.decoder)
.transform(const LineSplitter()).asBroadcastStream() ;
/// Reads a single line from [stdin] asynchronously.
Future<String> _readStdinLine() async {
var lineCompleter = Completer<String>();
var listener = _stdinLineStreamBroadcaster.listen((line) {
if (!lineCompleter.isCompleted) {
lineCompleter.complete(line);
}
});
return lineCompleter.future.then((line) {
listener.cancel();
return line ;
});
}
All these async API readLine*() based solutions miss the syntactic sugar which gives you the ability to do everything without synchronous blocking, but written like synchronous code. This is even more intuitive coming from other languages where you write code to execute synchronously:
import 'dart:convert';
import 'dart:io';
Future<void> main() async {
var lines = stdin.transform(utf8.decoder).transform(const LineSplitter());
await for (final l in lines) {
print(l);
}
print("done");
}
The key takeaway here is to make use of async and await:
async on your method is required, as you're using await to interface with asynchronous API calls
await for is the syntax for doing "synchronous-like" code on a Stream (the corresponding syntax for a Future is just await).
Think of await like "unwrapping" a Stream/Future for you by making the following code execute once something is available to be handled. Now you're no longer blocking your main thread (Isolate) to do the work.
For more information, see the Dart codelab on async/await.
(Sidenote: The correct way to declare any return value for an async function is to wrap it in a Future, hence Future<void> here.)
You can use the following line to read a string from the user:
String str = stdin.readLineSync();
OR the following line to read a number
int n = int.parse(stdin.readLineSync());
Consider the following example:
import 'dart:io'; // we need this to use stdin
void main()
{
// reading the user name
print("Enter your name, please: ");
String name = stdin.readLineSync();
// reading the user age
print("Enter your age, please: ");
int age = int.parse(stdin.readLineSync());
// Printing the data
print("Hello, $name!, Your age is: $age");
/* OR print in this way
* stdout.write("Hello, $name!, Your age is: $age");
* */
}
You could of course just use the dcli package and it's ask function
Import 'package: dcli/dcli.dart':
Var answer = ask('enter your name');
print (name);
Use the named validator argument to restrict input to integers.
To read from the console or terminal in Dart, you need to:
import 'dart:io' library
store the entered value using stdin.readLineSync()!
parse the input into an int using int.parse(input) if necessary
Code:
import 'dart:io';
void main() {
String? string;
var number;
stdout.writeln("Enter a String: ");
string = stdin.readLineSync()!;
stdout.writeln("Enter a number: ");
number = int.parse(stdin.readLineSync()!);
}

Resources