기본 콘텐츠로 건너뛰기

[Flutter] Flutter - Forms & Gestures

User interaction

Forms

  • 유효한 입력을 받는 Form 만들기
  • 자동으로 입력 창에 초점 맞추기
  • 입력 창에 입력된 값 회수하기

Gestures

  • 어떻게 제스처를 인식하고 반응하는 지에 관한 내용
  • ex) taps, drags, and scaling

Forms

어떻게 유효한 입력 값을 받는 Forms을 만들까?

  1. GlobalKey를 가진 Forms 생성.
  2. validation logic을 가지는 TextFormField 추가.
  3. 유효한 경우에만 Form을 제출하는 button 생성.
code</>
import 'package:flutter/material.dart';

// Define a custom Form widget.
class MyCustomForm extends StatefulWidget {
  const MyCustomForm({super.key});

  @override
  MyCustomFormState createState() {
    return MyCustomFormState();
  }
}

// Define a corresponding State class.
// This class holds data related to the form.
class MyCustomFormState extends State<MyCustomForm> {
  // Step 1. Create a global key that uniquely identifies the Form widget
  // and allows validation of the form.
  //
  // Note: This is a `GlobalKey<FormState>`,
  // not a GlobalKey<MyCustomFormState>.
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    // Build a Form widget using the _formKey created above.
    return Form(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Add TextFormFields and ElevatedButton here.
          Step 2. 
          TextFormField(
            // The validator receives the text that the user has entered.
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter some text';
              }
              return null;
            },
          ),
          Step 3.
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 16.0),
            child: ElevatedButton(
              onPressed: () {
                // Validate returns true if the form is valid, or false otherwise.
                if (_formKey.currentState!.validate()) {
                  // If the form is valid, display a snackbar. In the real world,
                  // you'd often call a server or save the information in a database.
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('Processing Data')),
                  );
                }
              },
              child: const Text('Submit'),
            ),
          ),
        ],
      ),
    );
  }
}

버튼이 눌러졌을 때 어떻게 입력 창에 focus를 두도록 만들까?

  1. FocusNode 생성.
  2. FocusNode 를 TextField에 전달.
  3. 버튼이 눌러졌을 때 focus 를 TextField에 전달.
code</>
// Define a custom Form widget.
class MyCustomForm extends StatefulWidget {
  const MyCustomForm({super.key});

  @override
  State<MyCustomForm> createState() => _MyCustomFormState();
}

// Define a corresponding State class.
// This class holds data related to the form.
class _MyCustomFormState extends State<MyCustomForm> {
  // Step 1. Define the focus node. To manage the lifecycle, create the FocusNode in
  // the initState method, and clean it up in the dispose method.
  late FocusNode myFocusNode;

  @override
  void initState() {
    super.initState();

    myFocusNode = FocusNode();
  }

  @override
  void dispose() {
    // Clean up the focus node when the Form is disposed.
    myFocusNode.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Text Field Focus'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            // The first text field is focused on as soon as the app starts.
            const TextField(
              autofocus: true,
            ),
            // The second text field is focused on when a user taps the
            // FloatingActionButton.
            Step 2. 
            TextField(
              focusNode: myFocusNode,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        // When the button is pressed,
        // Step 3. give focus to the text field using myFocusNode.
        onPressed: () => myFocusNode.requestFocus(),
        tooltip: 'Focus Second Text Field',
        child: const Icon(Icons.edit),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

사용자가 입력한 값을 어떻게 회수할까?

  1. TextEditingController 이용.
  2. TextEditingController 를 TextField에 적용.
  3. 회수한 값을 조작(예를 들어 화면에 띄우기)
code</>
// Define a custom Form widget.
class MyCustomForm extends StatefulWidget {
  const MyCustomForm({super.key});

  @override
  State<MyCustomForm> createState() => _MyCustomFormState();
}

// Define a corresponding State class.
// This class holds the data related to the Form.
class _MyCustomFormState extends State<MyCustomForm> {
  // Step 1. Create a text controller and use it to retrieve the current value
  // of the TextField.
  final myController = TextEditingController();

  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    myController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Retrieve Text Input'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        Step 2. 
        child: TextField(
          controller: myController,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        // When the user presses the button, show an alert dialog containing
        // the text that the user has entered into the text field.
        onPressed: () {
          showDialog(
            context: context,
            builder: (context) {
              return AlertDialog(
                // Step 3. Retrieve the text the that user has entered by using the
                // TextEditingController.
                content: Text(myController.text),
              );
            },
          );
        },
        tooltip: 'Show me the value!',
        child: const Icon(Icons.text_fields),
      ),
    );
  }
}

Gestures

Flutter의 gesture system은 2가지 분리된 layer 들로 이루어집니다.
  • Pointers: 포인터의 위치와 움직임에 대한 것
  • Gestures: 여러 개의 포인터 움직임에 의미를 부여한 것

Pointers

  • PointerDownEvent: 특정 위치에 접촉했을 때
  • PointerMoveEvent: 다른 위치로 움직였을 때
  • PointerUpEvent: 스크린에서 손을 떼었을 때
  • PointerCancelEvent: 더 이상 입력이 없을 때

Tap

onTapDown: 스크린 접촉
onTapUp: 스크린 접촉 중지
onTap: onTapDown => onTapUp
onTapCancel: 스크린에 접촉하고 있는 것 만으로 tap 을 유발하지 않음

Double tap

onDoubleTap: 같은 위치에서 빠르게 두 번 터치 했을 때

Long press

onLongPress: 오래 같은 위치에서 접촉한 상태를 유지할 때

Vertical drag

onVerticalDragStart: 스크린에 접촉한 채 수직으로 움직일 때
onVerticalDragUpdate: 수직으로 움직이기 시작하고 계속 수직으로 움직일 때onVerticalDragEnd: 수직으로 움직이지 않고 접촉을 중단할 때

Horizontal drag

onHorizontalDragStart: 수평 방향으로 움직이기 시작할 때
onHorizontalDragUpdate: 수평 방향으로 움직이기 시작하고 계속 수평 방향으로 움직일 때
onHorizontalDragEnd: 수평 방향으로 움직이지 않고 접촉을 중단할 때

Pan

onPanStart: 스크린에 접촉한 후 수직 또는 수평 방향으로 움직이기 시작할 수도 있을 때, 
onHorizontalDragStart 또는 onVerticalDragStart 이 설정되어 있을 때 충돌을 일으킴
onPanUpdate: 움직이기 시작해서 계속 움직일 때
onHorizontalDragUpdate 또는 onVerticalDragUpdate 이 설정되어 있을 때 충돌을 일으킴
onPanEnd: 더 이상 움직이지 않고 접촉을 중단할 때 
onHorizontalDragEnd 또는 onVerticalDragEnd 이 설정되어 있을 때 충돌을 일으킴

어떻게 Gestures을 감지할까?

code</>
// The GestureDetector wraps the button.
GestureDetector(
  // When the child is tapped, show a snackbar.
  onTap: () {
    const snackBar = SnackBar(content: Text('Tap'));

    ScaffoldMessenger.of(context).showSnackBar(snackBar);
  },
  // The custom button
  child: Container(
    padding: const EdgeInsets.all(12.0),
    decoration: BoxDecoration(
      color: Colors.lightBlue,
      borderRadius: BorderRadius.circular(8.0),
    ),
    child: const Text('My Button'),
  ),
)

이 블로그의 인기 게시물

[모집] 2024학년도 1학기 신규인원 모집: 3/10(일) 마감

안녕하세요, 구글 기술 앰버서더, 성균관대학교 Google Developer Student Clubs 입니다! GDSC (Google Developer Student Clubs)는 Google에서 학생들이 개발/리더십 능력을 향상할 수 있도록 지원하는 대학생 커뮤니티 프로그램입니다. 성균관대학교 GDSC는 구글 코리아, Google for Developers, SW중심대학사업단 등 다양한 단체와 협업하여 구글 기술을 대중에 알리고 관련 행사를 주최하며, 이러한 프로그램을 통해 협업성, 인적 네트워킹 및 리더십을 향상할 수 있습니다.

[11월 행사] 머신러닝/인공지능 (ML/AI) 스터디 워크샵: 사전 신청 오픈! — Google Developers 전문가와 함께하는 머신러닝/인공지능 학습, 텐서플로우 실습 및 네트워킹 기회! (11/9 사전신청 마감)

  👉 사전 신청 종료 추가적인 사전 신청을 원하시는 경우 연락 페이지 를 통해서 문의하시길 바랍니다. 업데이트 (11/8): 본 행사는 정책상 참여자 분들께서 요청하실 경우 행사 참여 확인서를 발급해드릴 예정입니다. 행사 참석 당일날 스태프 분께 말씀하시면 됩니다. 업데이트 (11/9):  상세한 행사 정보가 부분적으로 오류가 있어서 정정했습니다. (행사 시작 시간은 변경되지 않았습니다.) 기타 문의하실 사항이 있으실 경우 연락 페이지를 통해서 문의주시면 감사하겠습니다.   안녕하세요, 성균관대학교 Google Developer Student Club (GDSC) 입니다. Google Developers 전문가 분들과 함께 저희 GDSC SKKU TensorFlow 팀에서 11월 10일 💻November ML/AI Study Workshop💻을 주최합니다! 👏🏼 프로그램에서는 TensorFlow 기초 이해부터 주요 신경망 모델링 및 학습까지 TensorFlow 기술 전반에 대한 실습이 진행되며 관련 전문가 분들과의 네트워킹 기회가 제공될 예정입니다. 🍔 또한 본 행사에서는 참가자분들을 위한 간식, 음료와 간단한 저녁식사도 준비되어 있습니다! 👇🏼 이벤트 상세 내용은 아래와 같습니다. 📍 일시: 11월 10일 (금) 16:00 ~ 20:30 📍 장소: 자연과학캠퍼스 화학관 1층 330102 첨단강의실 📍 참가대상: 성균관대학교 학부생 누구나 📍 프로그램 내용 I. TensorFlow 기초 이해 II. 주요 신경망 모델링 및 학습 (CNN, Cloud Run, RNN) III. 종료 및 네트워킹 📍 진행자 이영빈 님 (GDG Songdo Organizer) 한상준 님 (GDG Songdo Organizer) 권정민 님 (Google Developer Experts) 장현수 님 ((전)성균관대학교 박사) 📍 사전 신청링크 https://gdscskku.blogspot.com/mlai-study   머신러닝 및 인공지능 분야 및 Tenso

[글로벌 IT전문가와 킹고인의 만남 시즌2] 행사 신청/참석 안내

  글로벌 IT전문가와 킹고인의 만남 시즌2에 대해 많은 관심 감사드립니다! 본 웹페이지를 통해서 학우님들의 원활한 행사 신청 및 참석을 위해 GDSC Community Platform 사용법을 안내드리고자 합니다 [카카오톡으로 링크 접속하신 경우 안내] 카카오톡 내장 브라우저에서 Google 로그인 시 "액세스 차단됨: Bevy의 요청이 Google 정책을 준수하지 않습니다"로 표시되는 사례가 확인되었습니다. 구글 계정 보안 정책상 카카오톡 내장 브라우저 내 로그인을 허용하지 않은 관계로, 디바이스에 설치된 기본 브라우저(Google Chrome 등)를 통해서 신청하시길 바랍니다. 👉 글로벌 IT전문가와 킹고인의 만남 시즌2 신청하기 플랫폼 인프라스트럭처 운영사/제공자: Google LLC/Bevy Labs, Inc. 행사 신청하기 1. GDSC 이벤트 플랫폼 웹사이트에서 구글 계정을 이용해서 로그인을 합니다. 2. (처음 로그인하는 경우) Sign up 페이지에서 필요한 정보를 입력합니다. 3. 로그인인 된 상태일 경우 "RSVP for this event now!" 아래에 온라인/오프라인 참석을 선택할 수 있습니다. 희망하시는 참석 방법 오른쪽에 있는 RSVP 버튼을 클릭하시면 됩니다. 4. RSVP 클릭 후 참석자 (Attendee Information) 입력하세요. (한글 설명, 학번, 전공 등) 5. RSVP Confirmed가 표시될 경우 신청이 완료되었음을 확인하실 수 있습니다. 행사 참석하기 (온라인) 행사가 시작될 경우 행사 웹페이지에서 [Join Event] 버튼이 표시됩니다. [Join Event] 버튼을 클릭하시면 바로 참석하실 수 있습니다. 참고: 행사 신청하신 경우 시스템 상 자동으로 이메일을 통해서 안내드립니다.

[12월 행사] ⭐ GDSC에서 연합 해커톤💻 행사를 개최합니다! 🎉

신청 URL: https://festa.io/events/4457 신청 마감시간: 12월 22일 금요일 21시 안녕하세요, 성균관대학교 Google Developer Student Club (GDSC) 입니다.  12월 28일부터 29일까지 마루 180에서 서울여자대학교, 연세대학교, 한양대학교의 GDSC 지부와 연합한 해커톤 대회를 주최하고 있습니다. 본 프로그램에서 참가자들은 서울여자대학교, 연세대학교, 한양대학교 학생들과 연합하여 팀을 구성하고 기업의 API 혹은 자체 개발 상품을 활용한 집중 해킹을 진행하며, GDE(Google Developer Experts) 및 GDG(Google Developer Groups)의 멘토링을 받아 프로젝트를 개발하고, 제휴기업 세미나 청강 및 네트워킹을 진행합니다. 행사 참가자와 수상팀에게 식사와 상품도 제공될 예정입니다. 아래 링크를 통해 이벤트 상세 내용 확인 및 티켓 구입이 가능합니다.  신청은 12월 22일 금요일 21시까지입니다. https://festa.io/events/4457 타학교 학생들과 연합하며 팀워크를 키우고 싶으신 분, 프로젝트 개발 경험을 쌓고 자신의 분야에 전문성을 키우고 싶으신 분, 전문가 및 공통 관심사의 학우들과 정보를 교환하고 협력하고 싶으신 분 모두 환영입니다! 학부생 여러분들의 많은 관심 부탁드립니다. 🙌🏼  공동 주최:  GDSC Yonsei | GDSC SWU | GDSC Hanyang | GDSC SKKU | 알파코 K-디지털 플랫폼(DT 그라운드) 주관: 성균관대학교 SW중심대학사업단 후원:  Google for Developers,  MONSTER ENERGY,  Wrtn Technologies

[9월 행사] 구글 클라우드 스터디 워크샵: 사전 숙지사항

9월달 구글 클라우드 스터디 워크샵에 신청해주신 여러분 감사드립니다. 행사 참여에 앞서, 아래의 사전 숙지사항을 반드시 확인해주시기 바랍니다. 여러분의 원활한 참여를 위해 준비 사항을 지켜주시면 감사하겠습니다. 필수 물품: 개인 노트북 필수 : 워크샵 동안 여러분의 개인 노트북을 사용하게 되는 만큼, 필히 노트북을 지참해 주시기 바랍니다. 실물 해외 신용카드 (VISA/MasterCard): GCP 계정을 생성할 때 결제 정보가 필요합니다. 권장 물품: 노트북 충전기/멀티탭: 각자의 노트북을 사용할 예정이므로 충전이 필요한 기기를 위해 노트북 충전기 및 멀티탭을 지참하시는 것을 추천드립니다. 진행장소: 성균관대학교 자연과학캠퍼스(수원) 화학관 1층 330118 첨단강의실 Google Map:  https://maps.app.goo.gl/841LUEsJB1mB8YPG6 카카오 맵: https://kko.to/-64Z139x7E 네이버 지도:  https://naver.me/GNUIWpp5