My question is very simple, how can i create a loop that will loop a simple list of elements.
List li=["-","\\","|","/"];
this is my dart list and i want to create this simple animation.
Different ways to Loop through a List of elements
1 classic For
for (var i = 0; i < li.length; i++) {
// TO DO
var currentElement = li[i];
}
2 Enhanced For loop
for(final e in li){
//
var currentElement = e;
}
Notice the keyword final. It means single-assignment, a final variable's value cannot be changed.
3 while loop
var i = 0;
while(i < li.length){
var currentElement = li[i];
i++;
}
For the while loop, you will use var to reassign the variable value.
Try this code to loop through a list:
List li=["-","\\","|","/"];
for (var i=0; i<li.length; i++) {
print(li[i]);
}
As to the animation:
HTML
<p id="test">
test
</p>
Dart
import 'dart:html';
import 'dart:async';
main() async {
List li = ["-", "\\", "|", "/"];
for (var i = 0; i < 400000000; i++) {
querySelector('#test').text = li[i % 4];
(await new Future.delayed(const Duration(seconds: 1)));
}
}
Another ways of looping through a List in Dart:
Using the forEach method:
li.forEach((value) {
var currentElement = value;
});
Using a While Loop and an Iterator:
// First, get an iterator to the list:
var myListIter = li.iterator;
// Iterate over the list:
while(myListIter.moveNext()){
var currentElement = myListIter.current;
}
there are may methods to get a loop from list
for example we have this type of list
var mylist = [6, 7 ,9 ,8];
using for each method
mylist.forEach((e){
print(e);
});
using for Loop
for (int i=0 ; i<mylist.length; i++){
var e = mylist[i];
print(e);
}
Enhanced For loop
for (var e in mylist){
print(e);
}
using while loop
var i = 0;
while(i < mylist.length){
print(mylist[i]);
i++;
}
Related
Edit: i know, always call the first element on list, it isnt the point. i want to call numbers[0] func. and it regenerate new int.actually codes are not same which mine, i have a custom class which based on functions with random int and i need to use list of my custom class , so if i use func in list it will be awesome, how can i make new numbers list each time. when app start list regenerated, but i want when i call the list, it will regenerated
i want to print new int for each print but it prints same int , i tried so many thing and i cant figure out
void main{
int ramdomint(){
final _random = new Random();
int _num = _random.nextInt(100);
return _num;
}
List<int> numbers=[ramdomint(),ramdomint(),ramdomint()];
void printNums(){
for(var i=0;i<3;i++){
List<int> newNumbers =new List.from(numbers); //what can i use for this?
print(newNumbers[0]); //edit:i dont want [i], iwant to use ewNumbers[0] for new int for each time
}
}
printNums();
// expected new int for each but same one
}
solution from a friend:
import 'dart:math';
int get ramdomint => Random().nextInt(100);
List<int> get numbers => [ramdomint, ramdomint, ramdomint];
void main() {
for (var i = 0; i < 3; i++) {
print(numbers[0]);
}
}
Do not nest functions. Move ramdomint and printNums outside main function.
Add an empty list of arguments to the main function.
printNums: pass list of numbers as an argument.
printNums: you don't need to copy the list to the newNumbers if you want only to display the content of the list.
printNums: the problem is, you access only first element of the list (with 0 index).
import 'dart:math';
void main() {
List<int> numbers = [ramdomint(), ramdomint(), ramdomint()];
printNums(numbers);
}
int ramdomint() => Random().nextInt(100);
void printNums(List<int> numbers) {
// Easier way:
for (int item in numbers) {
print(item);
}
// Your way:
for (int i = 0; i < numbers.length; i++) {
print(numbers[i]);
}
}
EDIT:
According to #jamesdlin's comment, you can extend list class to randomize unique values in the list:
import 'dart:math';
void main() {
var numbers = <int>[]..randomize();
printNums(numbers);
}
void printNums(List<int> numbers) {
// Easier way:
for (int item in numbers) {
print(item);
}
// Your way:
for (int i = 0; i < numbers.length; i++) {
print(numbers[i]);
}
}
extension on List<int> {
void randomize({
int length = 3,
int maxValue = 100,
}) {
final generator = Random();
for (var i = 0; i < length; i++) {
add(generator.nextInt(maxValue));
}
}
}
The Problem here is that you are creating a list from the numbers list and accessing only the first element.
So it always prints the first element.
import 'dart:math';
void main() {
int ramdomint(){
final _random = new Random();
int _num = _random.nextInt(100);
return _num;
}
List<int> numbers=[ramdomint(),ramdomint(),ramdomint()];
void printNums(){
for(var i=0;i<3;i++){
print(numbers[i]);
}
}
printNums();
}
Don't want newNumbers, because it is already in List.
and the usage of List.from() - Documentation
Hope that works!
I want to have a new random number every time to print it, but it prints the same on. I tried so many thing, but I can't figure out what's wrong. Help me, please!
import 'dart:math';
int next_int() { return new Random().nextInt(100); }
void main()
{
List<int> list = [next_int(), next_int(), next_int()];
// expected new int each time but got the same one
for (var i = 0; i < 3; i++)
{
List<int> cur_list = new List.from(list);
print(cur_list[0]);
}
}
This code will work as you expect:
import 'dart:math';
int next_int() { return new Random().nextInt(100); }
void main()
{
List<int> list = [next_int(), next_int(), next_int()];
// expected new int each time but got the same one
for (var i = 0; i < 3; i++)
{
List<int> cur_list = new List.from(list);
print(cur_list[i]); // <= Use the index value stored in "i" instead of 0
}
}
This is the code I'm trying to use, which seems logical. But doesn't seem to be working.
MyAsFileName.prototype.getTotalScore = function() {
var totalScore = 0;
for (var i = 0; i < allQuestions.length; i++) {
totalScore += allQuestions[i].getCalculatedScore();
if (currentModule.allQuestions[i].parent.questionCorrect == true) {
knowledgePoints++;
} else {
knowledgePoints--;
}
}
debugLog("Total score: " + totalScore);
debugLog(knowledgePoints);
return totalScore;
}
I have allQuestions defined as below:
var allQuestions = Array();
I have knowledgePoints defined as:
this.knowledgePoints = 10;
I have questionCorrect defined as:
this.questionCorrect = false;
Second fresh attempt made with new class as answer below suggested (commented out for now until I figure out how to get working):
// package
// {
/*public class Quiz {
//public
var knowledgePoints: int = 10;
//public
var allQuestions: Array = new Array;
//public
var questionCorrect: Boolean = false;
//public
function getTotalScore(): int {
var totalScore: int = 0;
for (var i = 0; i < allQuestions.length; i++) {
totalScore += allQuestions[i].getCalculatedScore();
if (currentModule.allQuestions[i].parent.questionCorrect) {
knowledgePoints++;
} else {
knowledgePoints--;
}
}
debugLog("Total score: " + totalScore);
debugLog(knowledgePoints);
return totalScore;
}
}*/
//}
This code above outputs two errors in flash console:
Error 1. Attribute used outside of class.
Error 2. 'Int' could not be loaded.
It's a weird (and actually non-AS3 way) way to do this. Instead of creating a unnamed closure which refers weird variables from who-knows where, you should make it a normal AS3 class, something like that (in a file named Quiz.as):
package
{
public class Quiz
{
public var knowledgePoints:int = 10;
public var allQuestions:Array = new Array;
public var questionCorrect:Boolean = false;
public function getTotalScore():int
{
var totalScore:int = 0;
// Your code does not explain how you will that Array.
// It is initially an empty Array of length 0.
for (var i = 0; i < allQuestions.length; i++)
{
totalScore += allQuestions[i].getCalculatedScore();
if (currentModule.allQuestions[i].parent.questionCorrect)
{
knowledgePoints++;
}
else
{
knowledgePoints--;
}
}
// Not sure what it is.
debugLog("Total score: " + totalScore);
debugLog(knowledgePoints);
return totalScore;
}
}
}
Need add polymer paper-dropdown-menu in DOM.
I try this code:
makePapersElements() {
List _items = new List();
for (var i = 0; i < 13; i++) {
PaperItem item = new dom.Element.tag('paper-item');
item.text = i;
_items.add(item);
}
return _items;
}
And add nodes in PaperListbox then in PaperDropdownMenu:
List<PaperItem> items = makePapersElements();
var element = new dom.Element.tag('div');
PaperDropdownMenu dropMenu = new PaperDropdownMenu();
PaperListbox listBox = new dom.Element.tag('paper-listbox');
dropMenu.append(listBox);
listBox.nodes.addAll(items);
element.nodes.add(dropMenu);
$['example'].nodes.add(element);
It's not work currently:
How it can be done?
Update: Added Gist
https://gist.github.com/Rasarts/a0b6710e234ec8b4aa37f90e4cd14839
You can create PaperDropDownMenu and Paperlistbox with new Xxx(), no need for new dom.Element.tag('Xxx') because these elements contain a constructor for convenience where this is done already
https://github.com/dart-lang/polymer_elements/blob/7912e0e6641155505007a89140f11c25db14e3f8/lib/paper_listbox.dart#L61
https://github.com/dart-lang/polymer_elements/blob/7912e0e6641155505007a89140f11c25db14e3f8/lib/paper_dropdown_menu.dart#L69
I guess the issue is because you don't use the Polymer DOM API. See also https://github.com/dart-lang/polymer-dart/wiki/local-dom. Only when you enable full shadow DOM (with full polyfills whithout native support) then you don't need to use this API.
makePapersElements() {
List _items = new List();
for (var i = 0; i < 13; i++) {
PaperItem item = new PaperItem();
item.text = i;
_items.add(item);
}
return _items;
}
List<PaperItem> items = makePapersElements();
var element = new dom.Element.tag('div');
PaperDropdownMenu dropMenu = new PaperDropdownMenu();
PaperListbox listBox = new PaperListbox();
Polymer.dom(dropMenu).append(listBox);
// not sure this will work
Polymer.dom(listBox).childNodes.addAll(items);
// alternatively
var listboxDom = Polymer.dom(listBox);
for(var item in items) {
listboxDom.append(item);
}
Polymer.dom(this)appen(dropMenu);
// ro Polymer.dom(this.root)appen(dropMenu);
Polymer.dom($['example']).append(element);
Yes, I do it wrong. Example helped. Thanks.
https://github.com/bwu-dart-playground/polymer1/blob/12a4bca9c5c5b21c690af0bd4451407b64899a6e/so36689312_programmatically_create_paper_elements/web/pdm_element.dart#L36-L36
On an asp.net mvc page, I have a Kendo UI grid and a Kendo UI treeview. The treeview has checkboxes and the treeview has two tier data. Then once the grid is populated, I want to loop through the rows, find the corresponding id, then loop through the treeview and find the node with the same id and make it checked. The following is my code:
Grid code:
dataBound: function () {
var rows = this.tbody.children();
var dataItems = this.dataSource.view();
for (var i = 0; i < dataItems.length; i++) {
kendo.bind(rows[i], dataItems[i]);
bindCheckboxToId(dataItems[i].ID);
}
}
The javascript function to set the treeview node to be checked:
function bindCheckboxToId(id) {
var treeView = $("#treeview").data("kendoTreeView");
var myNodes = treeView.dataSource.view();
for (var i = 0; i < myNodes.length; i++) {
var children = myNodes[i].children.view();
alert(children.length);
if (children) {
for (var j = 0; j < children.length; j++) {
if (children[j].id === id) {
children[j].set("checked", true);
}
}
}
}
The problem is that, the children.length always comes as 0, although each parent node has two child nodes.
Thanks
We have to force the tree view to load the child nodes. The following is the updated code:
function bindCheckboxToId(id) {
var treeView = $("#treeview").data("kendoTreeView");
var myNodes = treeView.dataSource.view();
for (var i = 0; i < myNodes.length; i++) {
myNodes[i].load();
var children = myNodes[i].children.view();
//alert(children.length);
if (children) {
for (var j = 0; j < children.length; j++) {
if (children[j].id === id) {
children[j].set("checked", true);
}
}
}
}
}