본문 바로가기
flutter

Flutter 다이스게임만들기 3

by 멈추지않아 2022. 5. 29.
코딩셰프 강의를 보고 만든 파일입니다.
https://www.youtube.com/watch?v=mQX_kJKnZzk&list=PLQt_pzi-LLfoOpp3b-pnnLXgYpiFEftLB&index=3

오늘은 로그인페이지를 완성해보겠습니다.

class _diceState extends State<dice> {
  TextEditingController id=TextEditingController();
  TextEditingController password=TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('hello'),
        centerTitle: true,
        backgroundColor: Colors.purple,
        leading: IconButton(icon: Icon(Icons.menu), onPressed: () {}),
        actions: [
          IconButton(icon: Icon(Icons.search), onPressed: () {}),
        ],
      ),
      body:GestureDetector(

        onTap: (){FocusScope.of(context).unfocus();},
      child:SingleChildScrollView(
        child: Column(
          children: [
            Padding(
              padding: EdgeInsets.only(top: 50),
            ),
            Center(
                child: Image(
              image: AssetImage('image/bluelogo.png'),
              width: 170,
              height: 170,
            )),
            Form(
              child: Theme(
                data: ThemeData(
                    inputDecorationTheme: InputDecorationTheme(
                  labelStyle: TextStyle(
                    color: Colors.red,
                    fontSize: 20.0,
                  ),
                ),
                ),
                child: Container(
                  padding: EdgeInsets.all(40),
                  child: Column(
                    children: [
                      TextField(
                        controller: id,
                        decoration: InputDecoration(
                          labelText: 'Enter"dice"',
                        ),
                        keyboardType: TextInputType.text,
                      ),
                      TextField(
                        controller: password,
                        decoration: InputDecoration(
                          labelText: 'Enter"password"',
                        ),
                        keyboardType: TextInputType.text,
                      ),
                      SizedBox(
                        height: 40.0,
                      ),
                      ElevatedButton(
                          onPressed: (){},
                          child: Icon(Icons.arrow_forward),
                        style: ElevatedButton.styleFrom(
                          primary: Colors.yellow,
                          minimumSize: Size(100.0, 50.0),
                          onPrimary: Colors.blue,
                        ),
                      )
                    ],
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    )
    );
  }
}

우선 input요소를  조정할수 있는 TextEditingController를  두개 만들어줍니다. 글을 작성할수 있는게 2개니까 각자 맞게 한개씩 넣어주세요

TextEditingController id=TextEditingController();

이런식으로 TextEditingController 변수명=TextEditingController()만드시면 됩니다 약간 클래스 객체 생성이라고 생각하시면 됩니다.

TextField(
  controller: id,
  decoration: InputDecoration(
    labelText: 'Enter"dice"',
  ),
  keyboardType: TextInputType.text,
),

이런식으로 controller: TextEditingController 이런식으로 각각 넣어주면이제 저 변수에 접근해서  TextField관련 내용을 받아올수 있습니다.

이런식으로 text에 우리가 입력한 내용이 나오게 됩니다. 그럼 이거 활용해서 버튼을 누르면 아이디 비밀번호를 검사하고 그에따른 처리를 해주겠습니다.

우선 Dice.dart파일을 lib밑에 만들어 주세요

그리고 임시로 이렇게 넣어주세요

import 'package:flutter/material.dart';

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

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

class _DiceState extends State<Dice> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("주사위 게임"),
        centerTitle: true,
        backgroundColor: Colors.purple,
      ),
    );
  }
}

다시 main.dart파일로 오셔서

젤 밑으로 완전히 빠져나와서 

void showSnackBar(BuildContext context,String text) {
  ScaffoldMessenger.of(context).showSnackBar(SnackBar(
    content: Text(
      text,
      textAlign: TextAlign.center,
    ),
    duration: Duration(seconds: 2),
    backgroundColor: Colors.blue,
  ));
}

이렇게 함수를 만들어주세요

스낵바를 만들어주는 편리한 함수입니다. 어느 요소에서 보여줄것인지 정해주는 context 어떤 글자를 보여주는 text 두 인자를 받아서 실행 시켜 줍니다.

textalign은 글자 위치 처음 중간 끝을 정해주고 duration은 snackbar 지속시간을 정해주고 backgroundcolor는 스낵바 배경색을 정해 줍니다.

ElevatedButton(
    onPressed: (){
      if (id.text == 'dice' &&
          password.text == '1234') {
        Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) => Dice()),
        );
      } else if (id.text != 'dice' &&
          password.text == '1234') {
        showSnackBar(context,"아이디를 확인해주세요");
      } else if (id.text == 'dice' &&
          password.text != '1234') {
        showSnackBar(context,"비밀번호를 확인해주세요");
      }else{
        showSnackBar(context,"아이디와 비밀번호를 확인해주세요");
      }
    },
    child: Icon(Icons.arrow_forward),
  style: ElevatedButton.styleFrom(
    primary: Colors.yellow,
    minimumSize: Size(100.0, 50.0),
    onPrimary: Colors.blue,
  ),
)

그리고 이런식으로 버튼 onpressed에 넣어줍니다. 먼저 아이디와 비밀번호 같은지 검사하고  맞으면 Dice 페이지로 이동

틀리면 아이디 틀리고 비밀번호 1234 맞는지 확인 맞으면 아이디를 확인해주세요 라는 스낵바 뛰우기

또 아니면 아이디 맞고 비밀번호 틀리는지 확인 비밀번호를 확인해주세요 스낵바 출력

그것도 아니면 아이디와 비밀번호를 확인해주세요 출력

이런 내용의 함수입니다. 그럼 확인 해보면

이렇게 잘뜨는걸 확인 했습니다. 그런데 비밀번호는  형식이  바뀌면 좋으니까 수정해보겠습니다.

TextField(
  controller: password,
  decoration: InputDecoration(
    labelText: 'Enter"password"',
  ),
  keyboardType: TextInputType.text,
),

여기 두번째 TextField가 비밀번호 입력하는 부분이니까

obscureText: true,

이거를 추가해줍니다

TextField(
  obscureText: true,
  controller: password,
  decoration: InputDecoration(
    labelText: 'Enter"password"',

  ),
  keyboardType: TextInputType.text,
),

이렇게 숨겨지는걸 확인했습니다

내일은 본격적으로 주사위 굴리는걸 만들어 보겠습니다.

'flutter' 카테고리의 다른 글

flutter 다이스게임만들기 5 마지막  (0) 2022.05.31
Flutter 다이스게임만들기 4  (0) 2022.05.30
Flutter 다이스게임 만들기 2  (0) 2022.05.28
flutter 다이스게임 만들기  (0) 2022.05.27
flutter 5일차 statefulWidget  (0) 2022.05.26