728x90

플러터 BottomNavigationBar 예제를 나중에 활용하는데 도움될 수 있게 작성해본 예제다.

BottomNavigationBar 검색하면 단순한 것이 대부분이라 향후 기능 구현시 활용 목적으로 약간 더 추가했다.

 

import 'package:flutter/material.dart';
 
void main() {
  runApp(MyApp());
}
 
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}
 
class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
        brightness: Brightness.light,
      ),
      debugShowCheckedModeBanner: false,
      home: const MyHomePage(title: '플러터 데모 Main'),    );
  }
}
 
// Android Studio 에서 stful 엔터를 치면 자동으로 만들어진다.
// 여기에서 클래스 이름만 지정하면 자동으로 만들어진다.
class MyHomePage extends StatefulWidget {
  final String title; // 선언한 변수는 final을 붙여야 한다.
  const MyHomePage({Key? key, required this.title}) : super(key: key);
 
  @override
  _MyHomePageState createState() => _MyHomePageState();
  // Stateless 위젯과 다른 점은 createState() 메소드를 통해
  // 상태를 담당하는 클래스를 지정할 수 있다.
}
 
// 클래스 이름 앞에 _가 붙어 있으면 private 클래스로 본다.
// 다트에서는 Java와 같이 public, protected, private 같은 접근 제어자 키워드 없음
class _MyHomePageState extends State<MyHomePage> {
  int _selectedIndex = 0// _를 붙이면 private
  static const TextStyle optionStyle =
  TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
 
  static const List<Widget> _widgetOptions = <Widget>[
    Text(
      'Index 0: Home',
      style: optionStyle,
    ),
    CallsfloatBtn(), // class 호출
    Text(
      'Index 2: School',
      style: optionStyle,
    ),
  ];
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('BottomNavigationBar Sample'),
      ),
      body: Center(
        child: _widgetOptions.elementAt(_selectedIndex),
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _selectedIndex, // 선택된 Index
        backgroundColor: Colors.grey[200], //Bar의 배경색
        selectedItemColor: Colors.amber[800],
        selectedFontSize: 15//선택된 아이템의 폰트사이즈
        unselectedFontSize: 12//선택 안된 아이템의 폰트사이즈
        onTap: _onItemTapped,
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business),
            label: 'Business',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.school),
            label: 'School',
          ),
        ],
      ),
    );
  }
 
  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }
}
 
class CallsfloatBtn extends StatefulWidget {
  const CallsfloatBtn({Key? key}) : super(key: key);
 
  @override
  _CallsfloatBtnState createState() => _CallsfloatBtnState();
}
 
class _CallsfloatBtnState extends State<CallsfloatBtn> {
  int _counter = 0;
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center, // 중앙정렬
          children: <Widget>[
            Text(
              '당신은 버튼을 눌렀어요 :',
              softWrap: false// 텍스트가 영역을 넘어갈 경우 줄바꿈 여부
              style: Theme.of(context).textTheme.headline5,
            ),
            Text(
              '$_counter 번',
              style: TextStyle(fontSize: 25),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
 
  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }
}
 

 

참고자료

https://blog.logrocket.com/how-to-build-a-bottom-navigation-bar-in-flutter/

 

How to build a bottom navigation bar in Flutter - LogRocket Blog

This tutorial demonstrates how to build, integrate, and customize a bottom navigation bar in a Flutter app.

blog.logrocket.com

 

'Flutter 앱 > Layout' 카테고리의 다른 글

Flutter CustomScrollView  (0) 2022.06.21
Flutter Drawer Widget  (0) 2022.06.16
Flutter Layout  (0) 2021.12.26
Flutter Theme(테마) 변경  (0) 2021.12.24
Flutter TabBar  (0) 2021.12.22
블로그 이미지

Link2Me

,