ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • TestFild + GestureDetector 위젯
    프로그래밍 공부 메모/flutter 2022. 6. 1. 22:59
     TextEditingController controller = TextEditingController();
     
    텍스트 필드의 데이터를 컨트롤 하기위한 클래스(TextDditingController)
    컨트롤러를 더이상 사용하지 않을땐 리소스 낭비를 하지 않기위해 dispose메소드를 사용한다
    텍스트 필드의 속성에 controller 변수를 넣으면 간단히 연결된다!
     
    ※ 스넥바 위젯을 잘 쓰지 않는듯 하다 찾아보니 토스트 메시지를 많이 쓰는것 같다
    스넥바를 사용하기 위해 ' BuildContext context ' 개념과 함께 알아햐 한다
    GestureDetector 화면 전체가 버튼처럼 사용자의 터치(행동)에 반응, 한번 누르기, 길게 누르기 등
    onTap 속성에 값을전달, 버튼을 포함한 각종 이벤트에서 활용
     
    ※ onPress : 버튼을 클릭하는 행동에 관한 이벤트
    FocusNode : 포커스를 받는 즉정 위젯을 식별
    FocusScope: 어떤 위젯들까지 포커스를 받는지 범위를 나타냄
     

     

    import 'package:flutter/material.dart';
    
    import 'Dice.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'Dice game',
          home: LogIn(),
        );
      }
    }
    
    class LogIn extends StatefulWidget {
      @override
      State<LogIn> createState() => _LogInState();
    }
    
    class _LogInState extends State<LogIn> {
      TextEditingController controller =
          TextEditingController(); //컨트롤러를 더이상 사용하지 않을땐 리소스 낭비를 하지 않기위해 dispose메소드를 사용한다
      TextEditingController controller2 = TextEditingController();
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Log in'),
            backgroundColor: Colors.redAccent,
            centerTitle: true,
            leading: IconButton(icon: Icon(Icons.menu), onPressed: () {}),
            actions: <Widget>[
              IconButton(icon: Icon(Icons.search), onPressed: () {})
            ],
          ),
          body: Builder(
            builder: (context) {
              return SingleChildScrollView(
                child: Column(
                  children: [
                    Padding(
                      padding: const EdgeInsets.only(top: 50),
                      child: Center(
                        child: Image(
                          image: AssetImage(
                            'images/chef.gif',
                          ),
                          width: 170,
                          height: 190,
                        ),
                      ),
                    ),
                    Form(
                      child: Theme(
                        data: ThemeData(
                          primaryColor: Colors.teal,
                          inputDecorationTheme: InputDecorationTheme(
                            labelStyle: TextStyle(color: Colors.teal, fontSize: 15),
                          ),
                        ),
                        child: Container(
                          child: Padding(
                            padding: const 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: 40,
                                ),
                                ElevatedButton(
                                  onPressed: () {
                                    if (controller.text == 'dice' &&
                                        controller2.text == '1234') {
                                      Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                            builder: (context) => Dice()),
                                      );
                                    } else if (controller.text == 'dice' &&
                                        controller2 != '1234') {
                                      showSnackBar2(context);
                                    } else if (controller != 'dice' &&
                                        controller2.text == '1234') {
                                      showSnackBar3(context);
                                    } else {
                                      showSnackBar(context);
                                    }
                                  },
                                  child: Icon(
                                    Icons.arrow_forward,
                                    color: Colors.white,
                                    size: 35,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              );
            },
          ),
        );
      }
    }
    
    void showSnackBar(BuildContext context) {
      Scaffold.of(context).showSnackBar(
        SnackBar(
          content: Text(
            '로그인 정보를 다시 확인 하세요',
            textAlign: TextAlign.center,
          ),
          duration: Duration(seconds: 2),
          backgroundColor: Colors.blue,
        ),
      );
    }
    
    void showSnackBar2(BuildContext context) {
      Scaffold.of(context).showSnackBar(
        SnackBar(
          content: Text(
            '비밀번호가 일치 하지 않습니다',
            textAlign: TextAlign.center,
          ),
          duration: Duration(seconds: 2),
          backgroundColor: Colors.blue,
        ),
      );
    }
    
    void showSnackBar3(BuildContext context) {
      Scaffold.of(context).showSnackBar(
        SnackBar(
          content: Text(
            '철자를 확인하세요',
            textAlign: TextAlign.center,
          ),
          duration: Duration(seconds: 2),
          backgroundColor: Colors.blue,
        ),
      );
    }

     

    [ Dice 페이지 ]

    import 'package:flutter/material.dart';
    import 'dart:math';
    import 'package:fluttertoast/fluttertoast.dart';
    
    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 = 2;
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            centerTitle: true,
            title: Text('Dice game app'),
          ),
          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,
                    ),
                    Expanded(
                      child: Image.asset('images/dice$rightDice.png'),
                    ),
                  ]),
                ),
                ElevatedButton(
                  onPressed: () {
                    setState(() {
                      leftDice = Random().nextInt(6) + 1;
                      rightDice = Random().nextInt(6) + 1;
                    });
                    showToast('왼쪽 주사위 : $leftDice, 오른쪽 주사위 : $rightDice');
                  },
                  style: ElevatedButton.styleFrom(
                    primary: Colors.orange,
                  ),
                  child: Icon(Icons.play_arrow),
                ),
              ],
            ),
          ),
        );
      }
    }
    
    void showToast(String message) {
      Fluttertoast.showToast(
        msg: message,
        backgroundColor: Colors.grey[400],
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
      );
    }
    반응형
Designed by Tistory.