-
Flutter_05. If-Statement & 퀴즈 데이터> Frontend/Flutter 2023. 4. 22. 19:58
1. if 문으로 삼항을 대체.
Widget screenWidget = StartScreen(switchScreen); if (activeScreen == 'questions-screen') { screenWidget = const QuestionScreen(); }
2. Quiz Data 추가
Questions Page (questions_screen)에서 사용될 Quiz와 Answer 모음을 첨부
questions.dart 페이지는 아래와 같이 생겼는데,
const questions = [ QuizQuestion( 'What are the main building blocks of Flutter UIs?', [ 'Widgets', 'Components', 'Blocks', 'Functions', ], ), ];
여기서, QuizQuestion Class 로 감싸서 나중에 연결할 예정.
class QuizQuestion { const QuizQuestion(this.text, this.answers); final String text; final List<String> answers; }
3. Quiz Page 변경
-실제 데이터와 연결하여 사용하기 전에, Quiz Page (questions_screen) 을 구성한다.
import 'package:basic101_01/components/answer_button.dart'; import 'package:flutter/material.dart'; class QuestionScreen extends StatefulWidget { const QuestionScreen({super.key}); @override State<QuestionScreen> createState() { return _QuestionScreenState(); } } class _QuestionScreenState extends State<QuestionScreen> { @override Widget build(BuildContext context) { return SizedBox( width: double.infinity, // use as much width you can. child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( 'The Question', style: TextStyle(color: Colors.white), ), const SizedBox( height: 30, ), AnswerButton('Answer1', () { print('Hello'); }), AnswerButton('Answer2', () {}), AnswerButton('Answer3', () {}), AnswerButton('Answer4', () {}), ], ), ); } }
- width: double.infinity를 사용하여, 사용 가능한 width의 최대 길이 사용.
- child: Column (세로) 형태의 구조를 가질 것이고, 중앙 정렬로, 진행.
- children: Quiz의 질문과 답 버튼 노출
- 여기서, 답 버튼은 컴포넌트로 빼서, 공통 사용할 것이다.
4. Answer Button Component로 만들기
import 'package:flutter/material.dart'; class AnswerButton extends StatelessWidget { const AnswerButton(this.answerText, this.onTap, {super.key}); //positional argument // const AnswerButton({super.key, required this.answerText, required this.onTap}); //required argument final String answerText; final Function() onTap; @override Widget build(BuildContext context) { return ElevatedButton( onPressed: onTap, style: ElevatedButton.styleFrom( backgroundColor: const Color.fromARGB(255, 33, 1, 95), foregroundColor: Colors.white, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(40)), padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 30), ), child: Text(answerText)); } }
- shape: 버튼의 형태를 설정 할 수 있다.
- Constructor에서 받는 arguments의 경우 아래와 같이 두개로 진행하였으니, 양자택일
const AnswerButton(this.answerText, this.onTap, {super.key}); //positional argument // or const AnswerButton({super.key, required this.answerText, required this.onTap}); //required argument
'> Frontend > Flutter' 카테고리의 다른 글
Flutter_07.Quiz App04_Map & For loops (마무리) (0) 2023.04.26 Flutter_06. QuizApp03_ Passing Data (0) 2023.04.24 Flutter_04. Rendering Contents conditionally (0) 2023.04.19 Flutter_03. Excercise (0) 2023.04.18 Flutter_20230414_02. StatefulWidget (0) 2023.04.17