Skip to content

Instantly share code, notes, and snippets.

@junddao
Created June 9, 2023 00:55
Show Gist options
  • Save junddao/24b8a6c5b92c1fc223a751bb8392c644 to your computer and use it in GitHub Desktop.
Save junddao/24b8a6c5b92c1fc223a751bb8392c644 to your computer and use it in GitHub Desktop.
dart 3.0_ destructuring

dart 3.0_ destructuring

Created with <3 with dartpad.dev.

// destructuring
// record로 넘어온 값을 한방에 변수에 할당해서 써주는 기술
// 어떤 구조든 패턴만 맞춰주면 destructuring 가능
void main() {
// final user = ('하하', 20);
// String name = user.$1;
// int age = user.$2;
// 이렇게 쓰지말고 아래와 같이 쓰자
final (name, age) = ('하하', 30);
print(name);
print(age);
print('---------------');
// list 를 분해하는것도 가능
final users = ['gkgk', 'hoho'];
final [String a, String b] = users;
print(a);
print(b);
print('---------------');
// 리스트에 특정 값을 가져오는 방법
// x = 1, y = 2, z = 8
final numbers = [1, 2, 3, 4, 5, 6, 7, 8];
final [x, y, ..., z] = numbers;
print(x);
print(y);
print(z);
// ... 은 한군데만 사용 가능
print('---------------');
// 중간 ... 값 가져다 쓰기 ...cc
final [xx, yy, ...cc, zz] = numbers;
print(xx);
print(yy);
print(zz);
print(cc);
print('---------------');
// 특정값 무시하기 _ 사용
final [xxx,_, yyy, ...ccc, zzz, _] = numbers;
print(xxx);
print(yyy);print(zzz);print(ccc);
print('---------------');
// map destructuring
final users2 = {'name': 'hoho', 'age': 11};
final {'name': name3, 'age': age3} = users2;
print(name3);
print(age3);
print('---------------');
// class matching
final devs = Devs(name: 'miro', age: 22);
final Devs(name: name4, age: age4) = devs;
print(name4);
print(age4);
}
class Devs{
final String name;
final int age;
Devs({
required this.name,
required this.age,
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment