[flutter] 9주 완성 프로젝트 캠프 학습일지 (유데미x스나이퍼팩토리): Controller, Navigator

KoEunseo·2023년 9월 22일
0

flutter

목록 보기
13/45

Controller

TextField, PageView와 같은 경우 관리가 필요하다.
컨트롤러를 생성해 해당 위젯 내 controller로 연결한 후 변수를 조작한다.

Controller 기본 사용법: Text

Widget build(BuildContext context) {
    var idController = TextEditingController(
      //1. 관리자 1고용. 초기값 설정도 할 수 있다.
      text: 'admin@naver.com',
    );
    //1. 관리자 2고용. 
    var pwController = TextEditingController();
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: Column(
            children: [
              TextField(
                controller: idController, //2. 관리자 배정
              ),
              TextField(
                controller: pwController, //2. 관리자 배정
              ),
              TextButton(
                onPressed: () {
                  print(idController.text); //3. 관리자 일한다
                  print(pwController.text);
                },
                child: const Text('Login'),
              ),
            ],
          ),
        ),
      ),
    );
  };

Controller 기본 사용법: Page

var pageController = PageController() // 고용한다.
PageView(
  controller: pageController,
  physics: NeverScrollableScrollPhysics, // 사용자가 스크롤(스와이프)하는것을 막는다.
  children: [
    ...
  ],
),
floatingActionButton: FloatingActionButton(
  onPressed: (){
    pageController.nextPage( // 일시킨다.
      duration: Duration(milliseconds: 500),
      curve: Curves.easeIn,
    ),
  },
  child: Text('next'),
),

페이지 라우팅을 하기 위해서 페이지 최상단은 Scaffold로 한다.
플러터에서 페이지는 스택 구조로 되어있다. push, pop을 통해 페이지 이동을 한다.
push할 때에는 context, 이동할 페이지를 매개변수로 전달한다.
pop할때는 가장 상단에 있는 페이지를 순서대로 pop하니 context만 전달하면 된다.

기본 구조

Navigator.push(
 context,
 MaterialPageRoute(
   builder: (context) => const NextPage(),
 ),
);

실습

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Page1(),
    );
  }
}

class Page1 extends StatelessWidget {
  const Page1({super.key});

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar:
          AppBar(), //automaticallyImplyLeading = true, 이기 때문에 자동으로 이전페이지로 돌려주는 버튼을 만든다.
      body: const Text('1'),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => const Page2(),
            ),
          );
        },
        child: const Text("2"),
      ),
    );
  }
}

class Page2 extends StatelessWidget {
  const Page2({super.key});

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: const Text('2'),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.pop(context);
        },
        child: const Text("1"),
      ),
    );
  }
}

if문 사용하기

블럭을 사용할 수 없다.
하나의 위젯에만 If문을 사용할 수 있다.

if(isLogin)
  Text('로그인되었습니다.')
else //else도 가능
  Text('로그인해주세요.')
  • 삼항연산자도 사용할 수 있다.
  • statefull 위젯의 경우 바로 final 변수에 접근할 수 없다.
    widget.name 이런식으로 해야함.

if문 외에도 아래 위젯을 사용해서 컨텐츠들이 보이게 할 지 컨트롤 할 수도 있다.

Checkbox

Checkbox(
  value: isChecked,
  onChanged: (v) {
    isChecked = v!;
    setState((){});
  },
)

Visibility

Visiblilty(
  visible: isLogin,
  child: Text('로그아웃'),
)

본 후기는 유데미-스나이퍼팩토리 9주 완성 프로젝트캠프 학습 일지 후기로 작성 되었습니다.

profile
주니어 플러터 개발자의 고군분투기

0개의 댓글