How to Create a Music Player app in flutter using Firebase (Cloud firestore,firebase storage) and 'music_player' plugin ?

How to Create a Music Player app in flutter using Firebase (Cloud firestore,firebase storage) and 'music_player' plugin ?


Hii Developers...

In this article, I will explain to you about How to Create a Music Player app in flutter using Firebase (Cloud firestore, firebase storage) and music_player plugin.



what we are going to build?




How to setup firebase for your music player app?

Step By Step:-
1) Go to the  Firebase Console (https://firebase.google.com) Sign up with your credentials.
2) Click on "Add Project" enter your app name, then Enable google analytics, select your account, and click on the "Create project" button.
3) After creating the project, we need an android platform so click on android.

firebase how to create a music app in flutter using firebase
firebase platform options

4) Enter package name , for package name goto the AndroidManifest.xml file which is under (android => app => src => debug => AndroidManifest.xml )

How to Create a Music Player app in flutter using Firebase (Cloud firestore,firebase storage) and 'music_player' plugin ?
AndroidManifest.xml file

5) Enter the name of your app, we don't need to put "Debug signing certificate SHA-1" so kept it blank, after putting all the details click on "Register app" button.
6) Download the config file and past it in-app directory ( android => app )

How to Create a Music Player app in flutter using Firebase (Cloud firestore,firebase storage) and 'music_player' plugin ?
google-service.json file

7) Copy and paste the small code snippets to the app and project level build.gradle file.
8) Go to the Storage and change the rules and do the same for the database.

How to Create a Music Player app in flutter using Firebase (Cloud firestore,firebase storage) and 'music_player' plugin ?
Firebase rules


How to Create a Music Player app in flutter using Firebase (Cloud firestore, firebase storage) and music_player plugin?

Step By Step:-
1) we need to use "music_player 0.1.4" package so goto the "music_player 0.1.4" package. ( https://pub.dev/packages/music_player )
2) Copy the dependency "music_player: ^0.1.4" and paste it in pubspec.yml file and paste the "firebase_storage" and "cloud_firestore" dependency.

How to Create a Music Player app in flutter using Firebase (Cloud firestore,firebase storage) and 'music_player' plugin ?
pubspec.yml file
3) Go to the app level build.gradle file and do some changes, change minSdkVersion from 16 to 21 and also add multiDexEnabled true.

How to Create a Music Player app in flutter using Firebase (Cloud firestore,firebase storage) and 'music_player' plugin ?
app level build.gradle file


4) We need to create these awesome bottom navigation bar.


How to Create a Music Player app in flutter using Firebase (Cloud firestore,firebase storage) and 'music_player' plugin ?
Bottom Navigation Bar
You may also like:- Create your first API using 'Deno' and fetch all the data from API in the Flutter app using 'http' package !!!




5) Code for bottom navigation bar:-


class _MyAppState extends State<MyApp> {
  int _currentindex=0;
  final tabs=[
    Home(),
    Upload(),
  ];
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Songs App",
      theme: ThemeData(
        primaryColor: Colors.blue,
        scaffoldBackgroundColor: Colors.grey[100],
      ),
      home:Scaffold(
        appBar: AppBar(
          title: Text("Songs App"),
        ),
        body:tabs[_currentindex],
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: _currentindex,
          items: [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              title: Text("Home"), 
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.cloud_upload),
              title: Text("Upload"),
            ),
          ],
          onTap: (index){
            setState(() {
              _currentindex=index;
            });
          },
        ), 

6) Code for uploading Image and song to the firebase (firebase storage):-

How to Create a Music Player app in flutter using Firebase (Cloud firestore,firebase storage) and 'music_player' plugin ?
Cloud Firestore

void selectimage() async{
   image=await FilePicker.getFile();
   setState(() {
     image=image;
     imagefilepath=basename(image.path);
      uploadImageFile(image.readAsBytesSync(),imagefilepath);
   });
 }

 Future<String> uploadImageFile(List<int> imagefile,String imagefilename) async{
   ref=FirebaseStorage.instance.ref().child(imagefilename);
   StorageUploadTask uploadTask=ref.putData(imagefile);
   imagedownurl=await (await uploadTask.onComplete).ref.getDownloadURL();
   return "success";
 }

  void selectfile() async{
  file = await FilePicker.getFile();
  setState(() {
    file=file;
    filename=basename(file.path);
    });
    uploadSongFile(file.readAsBytesSync(),filename);
  }

  Future<String> uploadSongFile(List<int> file,String filename) async{
   ref=FirebaseStorage.instance.ref().child(filename);
   StorageUploadTask uploadTask = ref.putData(file);
     downurl=await (await uploadTask.onComplete).ref.getDownloadURL();   
    return "success";
  }

void finalupload(){
  var data = {
    "song_name":songnameController.text,
    "artist_name":artistnameController.text,
    "song_url":downurl.toString(),
    "image_url":imagedownurl.toString(),
  };
  firestoreinstance.collection("songs").document().setData(data);
}


7) Code for fetching data from firebase (Cloud firestore) and displaying it in the form of cards using "ListView":-

How to Create a Music Player app in flutter using Firebase (Cloud firestore,firebase storage) and 'music_player' plugin ?

 Future getdata() async {
    QuerySnapshot qn =
        await Firestore.instance.collection('songs').getDocuments();
    return qn.documents;
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: getdata(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return Center(
              child: CircularProgressIndicator(),
            );
          } else {
            return ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (context, index) {
                return Card(
                  child: InkWell(
                    onTap: () => Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => Songpage(
                                title:snapshot.data[index].data["song_name"],
                                artist:snapshot.data[index].data["artist_name"],
                                url:snapshot.data[index].data["song_url"],
                                image:snapshot.data[index].data["image_url"]))),
                    child: Padding(
                      padding: EdgeInsets.all(20.0),
                      child: Text(
                        snapshot.data[index].data["song_name"],
                        style: TextStyle(
                          fontSize: 20.0,
                        ),
                        ),),),
                  elevation: 10.0,
                );},
            );}
        });



Whole Code for songpage.dart:-

import 'package:flutter/material.dart';
import 'package:music_player/music_player.dart';

class Songpage extends StatefulWidget {
  String artist;
  String title;
  String url;
  String image;

  Songpage({this.title, this.artist, this.url, this.image});

  @override
  _SongpageState createState() => _SongpageState();
}

class _SongpageState extends State<Songpage> {
  MusicPlayer musicPlayer;
  bool isplaying = false;

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  initPlatformState() {
    musicPlayer = MusicPlayer();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Songs App"),
      ),
      body: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        child: Center(
          child: Column(
            children: <Widget>[
              SizedBox(
                height: 30.0,
              ),
              Text(
                widget.title,
                style: TextStyle(
                  fontSize: 30.0,
                ),
              ),
              SizedBox(
                height: 15.0,
              ),
              Text(
                widget.artist,
                style: TextStyle(
                  fontSize: 15.0,
                ),
              ),
              SizedBox(
                height: 30.0,
              ),
              Card(
                child: Image.network(
                  widget.image,
                  height: 350.0,
                ),
              ),
              SizedBox(
                height: MediaQuery.of(context).size.height * 0.1,
              ),
              Row(
                children: <Widget>[
                  SizedBox(
                    width: 100.0,
                  ),
                  Expanded(
                    child: FlatButton(
                      onPressed: () {
                        setState(() {
                          isplaying = true;
                        });
                        musicPlayer.play(
                          MusicItem(
                            trackName: '',
                            albumName: '',
                            artistName: '',
                            url: widget.url,
                            coverUrl: '',
                            duration: Duration(seconds: 255),
                          ),
                        );
                      },
                      child: Icon(
                        Icons.play_arrow,
                        size: 50.0,
                        color: isplaying == true ? Colors.blue : Colors.black,
                      ),
                    ),
                  ),
                  Expanded(
                    child: FlatButton(
                      onPressed: () {
                        setState(() {
                          isplaying = false;
                        });
                        musicPlayer.stop();
                      },
                      child: Icon(
                        Icons.stop,
                        size: 50.0,
                        color: isplaying == true ? Colors.black : Colors.blue,
                      ),
                    ),
                  ),
                  SizedBox(
                    width: 100.0,
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}



Whole code for Main.dart :-

import 'package:flutter/material.dart';
import 'package:songsapp/screens/Home.dart';
import 'package:songsapp/screens/upload.dart';

void main() => runApp(MyApp());

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

class _MyAppState extends State<MyApp> {
  int _currentindex=0;
  final tabs=[
    Home(),
    Upload(),
  ];
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Songs App",
      theme: ThemeData(
        primaryColor: Colors.blue,
        scaffoldBackgroundColor: Colors.grey[100],
      ),
      home:Scaffold(
        appBar: AppBar(
          title: Text("Songs App"),
        ),
        body:tabs[_currentindex],
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: _currentindex,
          items: [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              title: Text("Home"),
              
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.cloud_upload),
              title: Text("Upload"),
            ),
          ],
          onTap: (index){
            setState(() {
              _currentindex=index;
            });
          },
        ), 
      ),
      routes:<String,WidgetBuilder> {
        '/upload':(BuildContext context) => new Upload(),
              }
            );
          }
        }
      

Whole code for Home.dart :-

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:songsapp/screens/songpage.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  Future getdata() async {
    QuerySnapshot qn =
        await Firestore.instance.collection('songs').getDocuments();
    return qn.documents;
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: getdata(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return Center(
              child: CircularProgressIndicator(),
            );
          } else {
            return ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (context, index) {
                return Card(
                  child: InkWell(
                    onTap: () => Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => Songpage(
                                title:snapshot.data[index].data["song_name"],
                                artist:snapshot.data[index].data["artist_name"],
                                url:snapshot.data[index].data["song_url"],
                                image:snapshot.data[index].data["image_url"]))),
                    child: Padding(
                      padding: EdgeInsets.all(20.0),
                      child: Text(
                        snapshot.data[index].data["song_name"],
                        style: TextStyle(
                          fontSize: 20.0,
                        ),
                        ),),),
                  elevation: 10.0,
                );},
            );}
        });
  }
}

Whole Code for upload.dart:-

import 'dart:io';
import 'package:path/path.dart';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class Upload extends StatefulWidget {
  @override
  _UploadState createState() => _UploadState();
}

class _UploadState extends State<Upload> {
  TextEditingController songnameController=TextEditingController();
  TextEditingController artistnameController=TextEditingController();
 File file,image;
 String filename,imagefilepath;
 StorageReference ref;
 final  firestoreinstance = Firestore.instance;
 var downurl,imagedownurl;

 void selectimage() async{
   image=await FilePicker.getFile();
   setState(() {
     image=image;
     imagefilepath=basename(image.path);
      uploadImageFile(image.readAsBytesSync(),imagefilepath);
   });
 }

 Future<String> uploadImageFile(List<int> imagefile,String imagefilename) async{
   ref=FirebaseStorage.instance.ref().child(imagefilename);
   StorageUploadTask uploadTask=ref.putData(imagefile);
   imagedownurl=await (await uploadTask.onComplete).ref.getDownloadURL();
   return "success";
 }

  void selectfile() async{
  file = await FilePicker.getFile();
  setState(() {
    file=file;
    filename=basename(file.path);
    });
    uploadSongFile(file.readAsBytesSync(),filename);
  }

  Future<String> uploadSongFile(List<int> file,String filename) async{
   ref=FirebaseStorage.instance.ref().child(filename);
   StorageUploadTask uploadTask = ref.putData(file);
     downurl=await (await uploadTask.onComplete).ref.getDownloadURL();   
    return "success";
  }

void finalupload(){
  var data = {
    "song_name":songnameController.text,
    "artist_name":artistnameController.text,
    "song_url":downurl.toString(),
    "image_url":imagedownurl.toString(),
  };
  firestoreinstance.collection("songs").document().setData(data);
}

  @override
  Widget build(BuildContext context) {
    return Center(
        child: Column(
          children: <Widget>[
            RaisedButton(
              onPressed: ()=>selectfile(),
              child: Text("Select Song"),
            ),
            RaisedButton(
              onPressed: ()=>selectimage(),
              child: Text("Select background image"),
            ),
            Padding(
              padding:EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
              child:TextField(
                controller: songnameController,
              decoration: InputDecoration(
                hintText: "Enter the name of Song"
              ),
            ),
            ),
            Padding(
              padding:EdgeInsets.fromLTRB(20.0,10.0, 20.0, 10.0),
              child:TextField(
                controller: artistnameController,
              decoration: InputDecoration(
                hintText: "Enter the name of the artist"
              ),
            ),
            ),

            RaisedButton(
              onPressed: (){
                finalupload();
              },
              child: Text("Submit"),
            )  
          ],
        ),
    );
  }
}
        

Thank you guys for spending your valuable time in reading this article, if you have any doubts please ask me those doubts in the comment section below.