Flutter state 메모리에 데이터 만들기

강정우·2023년 5월 14일
0

Flutter&Dart

목록 보기
19/82
post-thumbnail

class 생성

  • 프레임웤의 state 메모리에 데이터를 만들기 위해서는 우선 다른 font-end framework과는 다르게 데이터의 골조가 되는 class를 선언해줘야한다.

  • JAVA를 하면 당연한 소리지만 함수형 프로그래밍 (TS제외) => 객체지향으로 넘어오다보니 아직 적응이 안 돼서 다시 한 번 적는 것이다.

  • 우선 어떤 데이터를 생성할지 생각 후 그것에 맞는 class를 생성한다.

  • lib > models라는 폴더를 생성후 거기에 class를 생성한다.

class QuizQuestion {
  const QuizQuestion(this.text, this.answers);

  final String text;
  final List<String> answers;
}

data 생성

  • 위 청사진(class)에 맞춰 이제 데이터를 작성한다.
const questions = [
  QuizQuestion(
    'What are the main building blocks of Flutter UIs?',
    [
      'Widgets',
      'Components',
      'Blocks',
      'Functions',
    ],
  ),
  QuizQuestion('How are Flutter UIs built?', [
  ...

data 사용

class _QuestionsScreenState extends State<QuestionsScreen> {
  
  Widget build(context) {
    var currentQuestion = questions[0];

    return SizedBox(
      width: double.infinity,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(currentQuestion.text,
              style: const TextStyle(color: Colors.white)
              ),
          const SizedBox(height: 30),
          ...currentQuestion.getShuffledAnswers().map((answer) {
            return AnswerButton(answerText: answer, onTap: () {});
          }),
        ],
      ),
    );
  }
}
  • 현재 코드는 생성된 data에서 오직 첫번째 문제만을 가져오는 코드이다.

  • 이때 4지 선다를 보여줄 map함수는 기존의 데이터를 반환하는 것이 아닌 새로운 메모리에 참조되어 새로운 값이 return 된다.
    즉, 기존의 데이터를 건들이지 않는다.
    반면 suffle함수는 기존의 데이터를 건드린다.

  • 그래서 추가적으로 List객체는 편리한 기능을 제공한다.
    바로 of이다.

class QuizQuestion {
  const QuizQuestion(this.text, this.answers);

  final String text;
  final List<String> answers;

  List<String> getShuffledAnswers() {
    final shuffledList = List.of(answers);
    shuffledList.shuffle();
    return shuffledList;
  }
}
  • of는 기존의 List을 복사해 새 List를 만든다. 그리고 매개변수로는 대상이 될 List를 받으면 된다.
    이렇게 되면 기존의 데이터를 건들이지 않고 of, shuffle methods chaining을 통해 가변의 shuffle된 리스트를 받을 수 있다.

  • Column 위젯의 children:[] 안에는 반드시 Widget 타입만이 들어갈 수 있다.
    이때 일반 List(currentQuestion)는 들어갈 수 없다는 것이다. 이때 사용할 수 있는 연산자가 바로 ... spread 연산자이다. 이는 JS에서도 봤고 있는 개념이다. dart에서도 똑같이 제공을 하며 굉장히 비슷한 기능을 제공한다.

  • 즉, ... 연산자를 사용하면 알아서 List에서 하나씩 해당 값을 꺼내준다는 것이다.
profile
智(지)! 德(덕)! 體(체)!

0개의 댓글