반응형

 

bottom Navigation Bar은 다음과 같이, 아래쪽에 메뉴를 만들때 유용하게 쓰인다. 

각 메뉴마다 다른 위젯을 만들어 사용할 수 있다.

 

bottom Navigation Bar의 특징: 

아이콘이 필수로 들어간다. 

각 파일들을 하나의 페이지로 바꿀때 유용하게 사용된다.

각 파일들은 클릭할때마다 처음상태로 적용된다. (버튼으로 상황이 바뀐것이, 다른곳에 갔다온경우 초기화된다.)

 

 

코드: main.dart와 first, second, third.dart가 존재한다.

main.dart

 


import 'package:flutter/material.dart';

import 'first.dart';
import 'second.dart';
import 'third.dart'; //각 파일들을 쓰기위한 헤더파일 

void main() => runApp(MyApp()); //main에서 MyApp이란 클래스를 호출한다.


class MyApp extends StatelessWidget { //MyApp 클래스 선언
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false, //오른쪽위 debugBanner 없애기
      title: 'bottomNavigationBar',
      home: MyPage(),
    );
  }
}

class MyPage extends StatefulWidget { // bottomNavigationBar은 반드시 Stateful이어야함. 
  @override
  _MyPageState createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {
  int currentIndex =0;
  final screens = [ //이게 하나하나의 화면이되고, Text등을 사용하거나, dart파일에 있는 class를 넣는다. 
    first(),
    second(),
    third(),
  ];
  Widget build(BuildContext context) {
    return Scaffold(
      body: screens[currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: currentIndex,
        onTap: (index) => setState(() =>currentIndex = index), //setState를 써야 바뀐다. 

        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'first',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.call),
            label: 'second',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.book),
            label: 'third',
          ),
        ],
      ),
    );
  }
}

main.dart에서 신경써야 할 부분은 Stateful로 만들어야 한다는 사실과, setState를 써야한다는 부분이다. 

first.dart(second, third는 이것과 Text만 다름)

import 'package:flutter/material.dart'; //flutter의 package를 가져오는 코드 반드시 필요


class first extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<first> {
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blue,
        elevation: 0,
        centerTitle: true,
        title: Text("first slide"), // second third 다름
      ),
      body: Center(child: Text('first',style: TextStyle(fontSize: 40))) //second third 다름
    );
  }
}

 

반응형

+ Recent posts