Data Types

Jun's Coding Journey·2023년 8월 9일
0

[Learn] Dart

목록 보기
4/6

Basic Data Types


All the types and functions in Dart comes from an object.

Because all data types come from an object, we can get access to all the methods within that object type.

void main() {
  String name = "John";
  bool alive = true;
  int age = 12;
  age.isEven;
  double money = 69.99;
  num x = 12; // can be both an int or a double 
}

 

Lists


A list is used to group a list of values within a single variable.

void main() {
  var numbers = [1, 2, 3, 4];
}
void main() {
  List<int> numbers = [1, 2, 3, 4];
}

 
A list also has its own sets of methods.

void main() {
  List<int> numbers = [1, 2, 3, 4];
  numbers.add(5);
}

 

Collection if


Collection if allows us to create a list with elements that may or may not be available depending on the result of the if statement.

void main() {
  var giveMeFive = true;
  var numbers = [
  	1,
  	2,
  	3,
  	4,
    if (giveMeFive) {
      numbers.add(5);
    },
  ];
  print(numbers);
}
void main() {
  var giveMeFive = true;
  var numbers = [
  	1,
  	2,
  	3,
  	4,
    if (giveMeFive) 5,
  ];
  print(numbers);
}

 

String Interpolation


String interpolation is a way of including variables into a text.

void main() {
  var name = "John";
  var greeting = "Hello everyone, my name is $name";
  print(greeting);
}

 
When running an operation we use curly brackets.

void main() {
  var name = "John";
  var age = 10;
  var greeting = "Hello everyone, my name is $name and I'm ${age + 2}";
  print(greeting);
}

 

Collection For


Collection For allows us to add elements from other variables.

void main() {
  var oldFriends = ["John", "Dave"];
  var newFriends = [
  	"Lewis",
    "Ralph",
    "Darren",
    for (var friend in oldFriends) "$friend"
  ]
  print(newFriends); // [Lewis, Ralph, Darren, John, Dave];
}

 

Maps


Maps are collection types that represents a set of key-value pairs.

Each key in a Map is unique, and it is used to access its associated value.

Dart automatically detects the variable as a map.

Values in keys can be any type.

It is recommended to use maps on classes.

void main() {
  var player = {
  	'name': 'John',
    'xp': 19.99,
    'superpower': false,
  };
}

 
Maps can be manually defined with fixed types.

void main() {
  Map<int, bool> player = {
  	1: true,
    2: false,
    3: true,
  };
}

 
Maps also have their own sets of methods.

void main() {
  var player = {
  	'name': 'John',
    'xp': 19.99,
    'superpower': false,
  };
  player.containsValue();
}

 

Sets


Set only specifies unique elements (no duplicates allowed).

void main() {
  var numbers = {1, 2, 3, 4};
}

profile
Greatness From Small Beginnings

0개의 댓글