Jin's Dev Story

[Flutter] 페이지 나누기 - Tab 본문

Web & Android/Flutter

[Flutter] 페이지 나누기 - Tab

woojin._. 2023. 9. 22. 22:35

동적인 UI 만드는 법

1. 현재 UI의 현재 상태를 저장할 state를 만든다.

  • 주의사항 : state 이므로 StatefulWidget으로 변경해야함!
  • tab을 0으로 지정해놨기 때문에 tab이 0이면 0번탭, 1이면 1번탭으로 변경됨 → ‘홈’ 이렇게 지정해도 됨
class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  var tab = 0; 

  (하단생략)

2. 그 state에 따라서 현재 UI가 어떻게 보일지 코드를 짜놓는다.

body: [ Text('홈페이지'), Text('샵페이지') ]
,

3. 유저가 state를 쉽게 조작할 수 있도록 기능을 구현한다.

  • onTap: 파라미터를 추가하여 tab = i; 하면 됨
  • state이므로 setState안에 넣어야 함
bottomNavigationBar: BottomNavigationBar(
    showUnselectedLabels: false,
    showSelectedLabels: false,
    currentIndex: pageNum,
    onTap: (i){
      setState(() {
				tab = i;
			})
    },
    items: [ 생략 ]
)

예제

import 'package:flutter/material.dart';
import 'package:instagram_pr/style.dart';
import './style.dart' as style;

void main() {
  runApp(
      MaterialApp(
      theme: style.theme,
      home: MyApp()
  ));
}

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  var tab = 0;  // 1. 현재 상태 저장

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: Text('Instagram'),
          actions: [
            IconButton(
              icon: Icon(Icons.add_box_outlined),
              onPressed: () {},
              iconSize: 30,
            )
          ]),
      body: [Home(), Text('샵페이지')][tab],  // 2. state에 따라 tab 보이는 상태 변경
      bottomNavigationBar: BottomNavigationBar(
        showSelectedLabels: false,
        showUnselectedLabels: false,
        onTap: (i){
          setState(() {
            tab = i;
          });
        },
        items: [
          BottomNavigationBarItem(icon: Icon(Icons.home_outlined), label: '홈'),
          BottomNavigationBarItem(icon: Icon(Icons.shopping_bag_outlined), label: '샵')
        ],
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
        itemCount: 3,
        itemBuilder: (c, i) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Image.network('https://codingapple1.github.io/kona.jpg'),
              Container(
                constraints: BoxConstraints(maxWidth: 600),
                padding: EdgeInsets.all(20),
                width: double.infinity,
                child: Column(
                  children: [
                    Text('좋아요 100'),
                    Text('글쓴이'),
                    Text('글내용')
                  ],
                ),
              )
            ],
          );
        }
    );
  }
}