본문 바로가기

Dart

A tour of the Dart language 4탄 [Spread Operator ... ]

반응형

순서가 조금 뒤죽박죽이 됐군요! 원래 인생은 계획대로 되지 않습니다. 이 글의 목표는 Spread Operator를 내가 이해할 수 있도록 공부하는 것 뿐이니까요! 

 

정의

리스트, 맵, set 리터럴에서 여러 element를 collection에 추가할 때 ...(Spead Operator)를 사용하면 여러 요소를 간단하게 추가할 수 있습니다.  

 

동기 

컬렉션 literals는 각각의 item들을 새로운 컬렉션으로 만들 때 적합합니다. 그러나 이러한 기존 항목들은 이미 다른 컬렉션에 저장되어 있는 경우가 많습니다. 이러한 문제를 해결하기 위해 Dart2.3은 여러 값을 집합에 추가할 수 있는 Spread Operator(...)를 통해 목록의 모든 값을 다른 목록에 쉽게 추가할 수 있도록 지원합니다. 

 

예제1 

 var list = [1, 2, 3];
  var list2 = [0, ...list];
  print(list2); 
  
  var coffeeList = ['espresso', 'coffee', 'latte'];
  var newCoffeeList = ['milk tea', ...coffeeList];
  print(newCoffeeList);
  
  //출력 
[0, 1, 2, 3]
[milk tea, espresso, coffee, latte]

새롭게 생성된 리스트에는 기존의 리스트 내용이 쉽게 담기는 것을 확인할 수 있습니다. 

하지만 만약 Spread Oparator를 사용해 가져올 값이 null인 상황이 발생할 수 있습니다. 그럴 경우 null-aware operator(...?)을 사용하여 예외를 방지할 수 있습니다. 

 

예제2

 var list;
  var list2 = [0, ...?list];
  assert(list2.length == 1);
  print(list2);
  

  var coffee;
  var newCoffee = ['espresso', ...?coffee];
  print(newCoffee);
  
  //출력
[0]
[espresso]

 

간단한 예제를 통해 Dart에서의 활용을 알아봤습니다. 이제 이 Spread Oparotor를 Flutter에도 적용해봐야겠습니다. 

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    List<String> coffee = ['Espresso', 'Americano', 'Caffe-latte'];

    return Scaffold(
      appBar: AppBar(
        title: Text('Spread Operator Sample'),
      ),
      body: SingleChildScrollView(
        child: Center(
            child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            ...List.generate(
              coffee.length,
              (index) => Center(
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Container(
                    height: 50,
                    width: double.infinity,
                    color: Colors.amber,
                    child: Text(
                      coffee[index],
                      textAlign: TextAlign.center,
                    ),
                  ),
                ),
              ),
            ),
          ],
        )),
      ),
    );
  }
}

완성된 화면입니다. 👍 

 

 

 

참고

https://velog.io/@sharveka_11/02tbh0f2 

 

https://dart.dev/guides/language/language-tour#spread-operator

반응형