Instantly share code, notes, and snippets.

@jebright /lists
Last active Sep 23, 2018

Embed
What would you like to do?
Dart Fundamentals - Lists - Creating
void main() {
//Fix lengthed list
var namesFixed = new List<String>(3);
namesFixed[0] = "Joe";
namesFixed[1] = "Frankie";
namesFixed[2] = "Tom";
//namesFixed[3] = "Kaboom!"; //this would be an error
log(namesFixed) ;
//Growable list
var namesGrowable = new List<String>();
namesGrowable.add("Joe");
namesGrowable.add("Frankie");
namesGrowable.add("Tom");
namesGrowable.add("Larry");
log(namesGrowable) ;
//List initialized upfront
List<String> names = ["Joe", "Frankie", "Tom"];
log(names);
names.add("Dave"); //Can add just fine, since this one is growable too!
log(names);
//Using filled to set placeholder values on a fixed length list of 3
var namesFilled = new List<String>.filled(3, "placeholder");
log(namesFilled); //prints placeholder 3 times...
namesFilled[0] = "Joe"; //Update first entry
namesFilled[1] = "Frankie"; //Update second entry
log(namesFilled);
//Using generate (useful to create a long list of something like test data or to call a generator function)
List<String> namesGenerated = new List<String>.generate(3, (i) => "Name ${i}");
log(namesGenerated);
}
void log(List<String> lst) {
lst.forEach((n) => print(n));
print('=========');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment