Flutter - #2 DefaultTabController

손세은·2023년 9월 7일
0

Flutter

목록 보기
2/4

DefaultTabController

1. 플러터에서 탭 바(Tab Bar)와 탭 뷰(Tab View)를 사용하여 다중 탭 페이지를 구현할 때 유용한 위젯

2. 위젯을 사용하는 기본 단계

1) DefaultTabController를 생성

2) length 속성을 통해 탭의 개수를 설정하고

3) child 속성에는 TabBar와 TabBarView 위젯을 만듭니다.

  • TabBar는 상단에 탭 바를 표시
  • TabBarView는 각 탭에 해당하는 컨텐츠를 표시

3. 기본 구조 예제

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 2, // 탭의 개수
        child: Scaffold(
          appBar: AppBar(
            title: Text('Tab Example'),
            bottom: TabBar(
              tabs: [
                Tab(text: 'Tab 1'),
                Tab(text: 'Tab 2'),
              ],
            ),
          ),
          body: TabBarView(
            children: [
              Center(child: Text('Content for Tab 1')),
              Center(child: Text('Content for Tab 2')),
            ],
          ),
        ),
      ),
    );
  }
}

이 코드에서는 DefaultTabController로 두 개의 탭을 가지고 있으며, 각 탭은 TabBar와 TabBarView에 의해 구성됩니다. 선택된 탭에 따라 해당 탭의 내용이 화면에 표시됩니다.

3. Example


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

  
  Widget build(BuildContext context) {
    List<String> list = [
      "tabBar 메뉴명1",
      "tabBar 메뉴명2",
      "tabBar 메뉴명3",
      "tabBar 메뉴명4",
    ];

    return DefaultTabController(
        length: <list>.length, //탭의 개수 지정
        child: Scaffold(  //appBar(bottom(TabBar(tabs)))
          appBar: AppBar(
            bottom: TabBar(
              tabs: List.generate(
                <list>.length,
                (index) => Tab(text: <list>[index]),
              ),
           ),   
        ),

          body: TabBarView(
            children: [
              //탭의 개수만큼 보여질 화면을 만든다.
            ],
          )

4. List.generator

       bottom: TabBar(
              tabs: List.generate(//<list>의 길이만큼 Tab을 생성한다. 
                <list>.length,
                (index) => Tab(text: <list>[index]),
              ),
      
``
profile
힙스터 개발자가 될래요

0개의 댓글

관련 채용 정보