본문 바로가기
카테고리 없음

플러터 체험기 3. 탭바 뷰 - 크롬 시뮬 작동 알아내다!

설 연휴 때 플러터 위젯 중 탭바 뷰(TabBarView) 사용법에 도전해 보았습니다!
관련 내용 공유드립니다.


탭바 뷰는  여러 페이지를 담고 있는 페이지 목록인데요.
상단 또는 하단 탭 버튼을 터치하면 마치 동기화되듯 탭바 뷰 페이지도 덩달아 따라서 이동하는 위젯입니다.
사용법이 좀 까다로와 헤메였습니다.

까다로운 조건 몇가지를 정리하면 아래와 같은데요.

1) 탭바 뷰는 항상 탭바와 함께 사용해야 합니다.
2)  DefaultTabController 라는 걸 사용하거나,  TabController 라는걸 생성해서 사용해야 합니다.
3) 탭의 갯수는 아래 3가지 항목 3박자가 모두 일치해야 합니다.
 3-1) TabController 의 length 갯수
 3-2) TabBar 위젯의 자식 요소 갯수
 3-3) TabBarView 위젯의 자식 요소 갯수

게다가 크롬 브라우저로 에뮬을 돌려보면 1가지가 잘 작동하지 않았는데요.
탭 버튼을 클릭시 페이지 이동은 문제 없으나
페이지를 마우스로 클릭 좌우로 스와이핑하면 작동하지 않았습니다.

원래 작동해야 하는데 말이죠.
대신 실제 기기로 테스트해보니 잘 되긴 하더라요.
결국 천신만고(?) 끝에 원인을 알아 내긴 했는데 크롬 브라우저에서 앱처럼 작동을 테스트하려면,
F12 개발자 도구 창을 띄운 다음 모바일웹 모드를 켜주어야 합니다. ( 이런.. )

 그러자 크롬 브라우저에서도 스와이핑 작동이 되더라구요. ( 야호! )

2가지 소스코드 방식이 있는데요.
DefaultTabController 사용 소스와 tabController 생성 소스 공개합니다!(2024. 2. 12 테스트)
tabController 가 추후 기능 확장이 더 용이하겠더라구요.

1. DefaultTabController 위젯를 사용하는 예제 소스

import 'package:flutter/material.dart';

void main() => runApp(const TopTabbarExample());

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

  @override
  State<TopTabbarExample> createState() => _TabbarExampleState();
}

class _TabbarExampleState extends State<TopTabbarExample> {
  @override
  Widget build(BuildContext context) {
    // 테마 데이터
    const textTheme = TextTheme(
      bodyLarge: TextStyle(fontSize: 30),
    );
    return MaterialApp(
      // 디버그 띠 감추기
      debugShowCheckedModeBanner: false,
      // 디폴트 탭 컨트롤러로 Scaffold를 감싼다.
      home: DefaultTabController(
        // 갯수는 딱 맞게 입력해주어야 한다.
        length: 4,
        child: Scaffold(
          appBar: AppBar(
            title: const Text("탭바 예제", style: TextStyle(color: Colors.white)),
            backgroundColor: Colors.blue,
            bottom: const TabBar(
              // 선택항목 색상
              labelColor: Colors.white,
              // 비선택항목 색상
              unselectedLabelColor: Color.fromARGB(255, 205, 196, 164),
              // 선택항목 밑줄 색상
              indicatorColor: Colors.white,
              tabs: [
                Tab(icon: Icon(Icons.info), text: "회사소개"),
                Tab(icon: Icon(Icons.business), text: "사업분야"),
                Tab(icon: Icon(Icons.repartition), text: "A/S센터"),
                Tab(icon: Icon(Icons.phone), text: "연락처"),
              ],
            ),
          ),

          // TabBarView 는 TabBar 와 함께 사용해야 함.
          body: TabBarView(
            children: [
              Center(child: Text("회사소개", style: textTheme.bodyLarge)),
              Center(child: Text("사업분야", style: textTheme.bodyLarge)),
              Center(child: Text("A/S센터", style: textTheme.bodyLarge)),
              Center(child: Text("연락처", style: textTheme.bodyLarge)),
            ],
          ),
        ),
      ),
    );
  }
}

2. tabController 를 생성해 사용하는 코드

import 'package:flutter/material.dart';

void main() => runApp(const TopTabbarExample());

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

  @override
  State<TopTabbarExample> createState() => _TabbarExampleState();
}

class _TabbarExampleState extends State<TopTabbarExample>
    with TickerProviderStateMixin {
  TabController? tabController;

  @override
  void initState() {
    tabController = TabController(length: 4, vsync: this);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // 테마 데이터
    const textTheme = TextTheme(
      bodyLarge: TextStyle(fontSize: 30),
    );
    return MaterialApp(
      // 디버그 띠 감추기
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text("탭바 예제", style: TextStyle(color: Colors.white)),
          backgroundColor: Colors.blue,
          bottom: TabBar(
            controller: tabController,
            // 선택항목 색상
            labelColor: Colors.white,
            // 비선택항목 색상
            unselectedLabelColor: const Color.fromARGB(255, 205, 196, 164),
            // 선택항목 밑줄 색상
            indicatorColor: Colors.white,
            tabs: const [
              Tab(icon: Icon(Icons.info), text: "회사소개"),
              Tab(icon: Icon(Icons.business), text: "사업분야"),
              Tab(icon: Icon(Icons.repartition), text: "A/S센터"),
              Tab(icon: Icon(Icons.phone), text: "연락처"),
            ],
          ),
        ),

        // TabBarView 는 TabBar 와 함께 사용해야 함.
        body: TabBarView(
          controller: tabController,
          children: [
            Center(child: Text("회사소개", style: textTheme.bodyLarge)),
            Center(child: Text("사업분야", style: textTheme.bodyLarge)),
            Center(child: Text("A/S센터", style: textTheme.bodyLarge)),
            Center(child: Text("연락처", style: textTheme.bodyLarge)),
          ],
        ),
      ),
    );
  }
}

이렇게 정리해 놓으면 크레이도 나중에 참조할 수 있겠지요 :)


소소한 팁이지만 플러터로 탭뷰 구현하는데 안 풀리는 분에게 도움이 되셨으면 하는 마음으로 올립니다.
오늘도 방문해주신 모든 분들, 감사합니다!