DEV Community

Paul Allies
Paul Allies

Posted on

Flutter: Simple Bottom Navigation Bar

Bottom Navigation Bar is a component that makes it easy to explore and switch between the top-level view in single click or tap.

  1. Create Flutter Project
  2. Create Screen
  3. Create Navigation Container

1. Create Flutter Project

$> flutter create --org com.yourdomain navexample
Enter fullscreen mode Exit fullscreen mode

2. Create Screen


import 'package:flutter/material.dart';

class Screen extends StatelessWidget {
  String title;
  Screen({this.title});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(title)),
      body: Center(
        child: Text(title),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

3. Create Navigation Container (main.dart)

import 'package:flutter/material.dart';
import 'package:navexample/screen.dart';

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

class NavObject {
  Widget screen;
  Icon navIcon;
  Text title;
  NavObject({this.screen, this.navIcon, this.title});
}

List<NavObject> navItems = [
  NavObject(
    screen: Screen(title: "Home"),
    navIcon: Icon(Icons.home),
    title: Text('Home'),
  ),
  NavObject(
    screen: Screen(title: "Settings"),
    navIcon: Icon(Icons.settings),
    title: Text('Settings'),
  ),
  NavObject(
    screen: Screen(title: "Share"),
    navIcon: Icon(Icons.share),
    title: Text('Share'),
  ),
];

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

class _MyAppState extends State<MyApp> {
  int _screenNumber = 0;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: navItems[_screenNumber].screen,
        bottomNavigationBar: BottomNavigationBar(
          type: BottomNavigationBarType.fixed,
          items: navItems
              .map((navItem) => BottomNavigationBarItem(
                    icon: navItem.navIcon,
                    title: navItem.title,
                  ))
              .toList(),
          currentIndex: _screenNumber,
          onTap: (i) => setState(() {
            _screenNumber = i;
          }),
        ),
      ),
    );
  }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)