# Magic 8 Ball

# 0. Final Product

  • 클릭시 인생 고민에 대한 답을 들려주는 magic 8 ball.
  • 대답은 유용하지 않을 수 있다.

image-20220127101907716

image-20220127101820873

# 1. Import Images

pubspec.yaml

flutter:

  uses-material-design: true

  assets:
    - images/

1
2
3
4
5
6
7
  • 폴더단위로 import를 한 후
  • Image.asset('images/ball$answerNumber.png') 와 같은 형태로 사용 가능하다.

# 2. Main

main.dart

import 'package:flutter/material.dart';
import 'dart:math';

void main() => runApp(const BallPage());

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

  
  Widget build(BuildContext context) {
    return MaterialApp(
        title: "Magic 8 Ball",
        home: Scaffold(
            backgroundColor: Colors.blue,
            appBar: AppBar(
              title: const Text('Ask me Anything'),
              backgroundColor: Colors.blue.shade900,
            ),
            body: BallContent()));
  }
}

class BallContent extends StatefulWidget {
  
  _BallContentState createState() => _BallContentState();
}

class _BallContentState extends State<BallContent> {
  int answerNumber = Random().nextInt(5) + 1;
  void rollBall() {
    setState(() {
      answerNumber = Random().nextInt(5) + 1;
    });
  }

  
  Widget build(BuildContext context) {
    return Container(
        child: Center(
            child: TextButton(
                onPressed: () {
                  rollBall();
                },
                child: Image.asset('images/ball$answerNumber.png'))));
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
  • setState를 통해서 화면로딩을 해준다.

  • 탈퇴를 왜 만들어? 아무도 못 탈퇴하는 사이트 만들고싶습니다.

  • 참고로 난 한번도 안만들어봄