🎞️프로젝트/flutter

[flutter] 로그인과 주사위 게임 만들기 (코딩셰프 조금 매운 맛)

2022. 3. 10. 21:22
반응형

 

snackBar은 하지 않았다. showSnackBar가 더이상 지원하지 않기 때문이다. 

하지만 text를 입력할 때 화면 밖을 눌렀을 때 입력창이 내려가는 GestureDetextor 때문에 Builder 위젯을 남겨두었다.

 

onPressed() - 버튼을 누를 때

onTap() - 버튼 외의 여러 위젯을 누를 때

 

Expanded를 사용하면 위젯을 지정 구역까지 꽉차게 만들 수 있다. flex로 비율을 지정할 수도 있다.

Image.asset() 을 사용하면 간편하게 이미지를 불러올 수 있다.

 

LogIn Widget 코드

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: LogIn(),
      title: 'Dice Game',
    );
  }
}

class LogIn extends StatefulWidget {
  const LogIn({Key? key}) : super(key: key);

  @override
  State<LogIn> createState() => _LogInState();
}

class _LogInState extends State<LogIn> {
  TextEditingController controller = TextEditingController();
  TextEditingController controller2 = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Log In'),
          centerTitle: true,
          elevation: 0.0,
          backgroundColor: Colors.redAccent,
          leading: IconButton(
            icon: Icon(Icons.menu),
            onPressed: () {},
          ),
          actions: [
            IconButton(onPressed: () {}, icon: Icon(Icons.search),)
          ],
        ),
        body: Builder(
        builder: (context) {
          return GestureDetector(
            onTap: (){
              FocusScope.of(context).unfocus();
            },
            child: SingleChildScrollView(
              child: Column(
                children: [
                  Padding(
                    padding: const EdgeInsets.fromLTRB(0.0, 20.0, 0.0, 0.0),
                    child: Center(
                      child: Image(
                        image: AssetImage('images/JjangGu.png'),
                        width: 170,
                        height: 190,
                      ),
                    ),
                  ),
                  Form(
                    child: Theme(
                      data: ThemeData(
                        primaryColor: Colors.teal,
                        inputDecorationTheme: InputDecorationTheme(
                            labelStyle: TextStyle(
                              color: Colors.teal,
                              fontSize: 15.0,
                            )
                        ),
                      ),
                      child: Container(
                        padding: EdgeInsets.all(40.0),
                        child: Column(
                          children: [
                            TextField(
                              controller: controller,
                              decoration: InputDecoration(
                                  labelText: "Enter 'Dice'"
                              ),
                              keyboardType: TextInputType.emailAddress,
                            ),
                            TextField(
                              controller: controller2,
                              decoration: InputDecoration(
                                  labelText: "Enter password"
                              ),
                              keyboardType: TextInputType.text,
                              obscureText: true,
                            ),
                            SizedBox(
                              height: 30,
                            ),
                            ElevatedButton(
                              onPressed: () {
                                if (controller.text == 'dice' &&
                                    controller2.text == '1234') {
                                  Navigator.push(context,
                                      MaterialPageRoute(
                                          builder: (BuildContext context) =>
                                              Dice()));
                                }
                                else if (controller.text == 'dice' && controller2
                                    .text != '1234') {

                                }
                                else if (controller.text != 'dice' && controller2
                                    .text == '1234') {

                                }
                                else {

                                }
                              },
                              child: Text('Login'),
                              style: ButtonStyle(
                                backgroundColor: MaterialStateProperty.all(
                                    Colors.redAccent),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  )
                ],
              ),
            ),
          );
        }
    )
    );
  }
}

 

Dice Widget 코드

 

class Dice extends StatefulWidget {
  const Dice({Key? key}) : super(key: key);

  @override
  State<Dice> createState() => _DiceState();
}

class _DiceState extends State<Dice> {
  int leftDice = 1;
  int rightDice = 1;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.redAccent,
      appBar: AppBar(
        title: Text('Dice Game'),
        centerTitle: true,
        elevation: 0.0,
        backgroundColor: Colors.redAccent,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Padding(
              padding: const EdgeInsets.all(32.0),
              child: Row(
               children: [
                  Expanded(child: Image.asset('images/dice$leftDice.png')),
                 SizedBox(width: 20.0,),
                 Expanded(child: Image.asset('images/dice$rightDice.png')),
               ],
              ),
            ),
            ElevatedButton(onPressed: (){
              setState(() {
                leftDice = Random().nextInt(6)+1;
                rightDice = Random().nextInt(6)+1;
              });
            },
              child: Icon(Icons.play_arrow),
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Colors.amber)
              ),
            ),
          ],
        )
      ),
    );
  }
}

 

 

실행 결과이다. 

반응형
저작자표시 (새창열림)

'🎞️프로젝트 > flutter' 카테고리의 다른 글

[flutter] 앱바 아이콘과 drawer 디자인 하기 (코딩셰프 강좌) - 220228  (0) 2022.02.28
'🎞️프로젝트/flutter' 카테고리의 다른 글
  • [flutter] 앱바 아이콘과 drawer 디자인 하기 (코딩셰프 강좌) - 220228
pkyung
pkyung
pkyung
성장하는 중
pkyung
전체
오늘
어제
  • 분류 전체보기
    • 🏆토이 프로젝트에서 생긴 일
    • 🤿백엔드 내실 채우기
    • 🍫카카오 테크 캠퍼스 2기 BE
    • 🍀spring
      • 스프링 입문
      • 스프링 핵심원리 기본
      • 스프링 jpa
      • 🐛debug
    • 🔒보안
    • 🌎infra
      • docker
      • kubernetes
      • cloud
    • 🌐web
      • HTTP 웹 기본 지식
    • 🔑알고리즘
      • baekjoon
      • programming language
    • 🎞️프로젝트
      • android
      • flutter
    • 📚수업
      • 교양과목
    • 💾database
    • ⚙settings
    • 2023 여름 모각코 - 절개와지조
    • 2024 겨울 모각코 - 내 장점은 algorit..

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 백준
  • 데이터베이스
  • 스택
  • sql
  • Docker
  • spring
  • mysql
  • 소수
  • be
  • BFS
  • HTTP
  • 카카오테크캠퍼스
  • 코드리뷰
  • Security
  • 객체지향의사실과오해
  • nginx
  • 객체지향
  • 파이썬
  • python
  • 김영한
  • 스프링
  • Java
  • 자바문자열
  • 자바
  • 문자열
  • 카테캠
  • 스프링기본
  • 스프링부트
  • springboot
  • JPA

최근 댓글

최근 글

hELLO · Designed By 정상우.
pkyung
[flutter] 로그인과 주사위 게임 만들기 (코딩셰프 조금 매운 맛)
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.