Skip to content

Instantly share code, notes, and snippets.

@jebright
Last active September 23, 2018 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jebright/4cee2d13d2c839f2a5f7fd2a5be8bb93 to your computer and use it in GitHub Desktop.
Save jebright/4cee2d13d2c839f2a5f7fd2a5be8bb93 to your computer and use it in GitHub Desktop.
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