goal : 새파일에 클래스를 생성하여main.dart
파일을 추상화하자.
main.dart
파일에 코드가 너무길어지고 복잡해지면서, 가독성과 코드의 효율이 떨어진다. 추상화작업이 이를 방지해준다.
지난번에 만들어놓은 퀴즈앱의main.dart
파일에서, 'question' 클래스의
객체 'q'에 총3개의 질문과 답을 저장했었다.
List<Question> q = [
Question(
questiontext: 'You can lead a cow down stairs but not up stairs.',
questionanswer: false),
Question(
questiontext:
'Approximately one quarter of human bones are in the feet.',
questionanswer: true),
Question(questiontext: 'A slug\'s blood is green.', questionanswer: true)
];
만약 질문의 수가 많아질수록,main.dart
파일의 코드는 훨씬 더 복잡해질것이다. 또한, 질문을 변경할때마다main.dart
파일을 수정해야할것이다.
이를 방지하기 위해 추상화작업을 진행할 것이다.
먼저, 새 파일quiz
를 생성하여 객체 'q'를 속성으로하는 'Quiz'클래스를 생성하자.
import 'question.dart';
class Quiz {
List<Question> q = [
Question(
questiontext: 'You can lead a cow down stairs but not up stairs.',
questionanswer: false),
Question(
questiontext:
'Approximately one quarter of human bones are in the feet.',
questionanswer: true),
Question(questiontext: 'A slug\'s blood is green.', questionanswer: true)
];
※Question.dart
파일을 'import'하여 'Question'타입을 정의해줘야 한다.※
이제,main.dart
파일에 'Quiz'클래스의 객체 'quiz'를 생성하자.
import 'question.dart';
'
'
List<Question> q = [
Question(
questiontext: 'You can lead a cow down stairs but not up stairs.',
questionanswer: false),
Question(
questiontext:
'Approximately one quarter of human bones are in the feet.',
questionanswer: true),
Question(questiontext: 'A slug\'s blood is green.', questionanswer: true)
];
'
'
import 'quiz.dart';
'
'
Quiz quiz = new Quiz();
'
'
※'Quiz'클래스는quiz.dart
파일에 있으므로 quiz.dart
파일을 'import'한다.※
'q'는 'Quiz'클래스의 속성이므로,main.dart
파일이 코드는 아래와 같이 변경된다.
child: Text(
q[questionNumber].questiontext,
'
'
onPressed: () {
if (q[questionNumber].questionanswer == true) {
print('correct');
'
'
nPressed: () {
if (q[questionNumber].questionanswer == false) {
print('correct');
'
'
'
'
child: Text(
quiz.q[questionNumber].questiontext,
'
'
onPressed: () {
if (quiz.q[questionNumber].questionanswer == true) {
print('correct');
'
'
nPressed: () {
if (quiz.q[questionNumber].questionanswer == false) {
print('correct');
'
'