Code Snippet For Bottom Tab Bar in Flutter

in #flutter2 years ago

Summary

In this post, I'll share the code snippet for building a botton-tab-bar in Flutter.
Please stay tuned for more updates. In my next post, I'll share a video tutorial in which I'll explain everything about the following code snippet step by step.

Code Snippet

Here goes the code snippet.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _index = 0;

  Widget getBody(int index) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            'This is body of index $index',
            style: Theme.of(context).textTheme.headline4,
          ),
        ],
      ),
    );
  }

  BottomNavigationBarItem getItem(String name, IconData data) {
    return BottomNavigationBarItem(
        icon: Icon(data), label: name, backgroundColor: Colors.black87);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: IndexedStack(
        children: [getBody(0), getBody(1), getBody(2), getBody(3), getBody(4)],
        index: _index,
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: [
          getItem('Home', Icons.home),
          getItem('Trending', Icons.local_fire_department),
          getItem('Favorites', Icons.star),
          getItem('Community', Icons.people),
          getItem('Settings', Icons.settings),
        ],
        currentIndex: _index,
        onTap: (index) {
          setState(() {
            _index = index;
          });
        },
      ),
    );
  }
}

Here are two screenshots for the above code snippet.

Sort:  


Congratulations @sagarkothari88!
You raised your level and are now a Minnow!

Support the HiveBuzz project. Vote for our proposal!