DEV Community

Paul Allies
Paul Allies

Posted on

4 3

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay