Blogging my journey of learning Full stack devlopment and creating an App to get a hands on knowledge.

Search This Blog

Friday, 31 March 2023

Firebase Firestore Database and Storage implementation for Flutter Project

  1. From your Flutter project directory, run the following command to install the core plugin:

    flutter pub add firebase_core

  2. Add following code to the root of your Flutter project,  

    import'package:firebase_core/firebase_core.dart'; import'firebase_options.dart'; Future main()async{ WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(  options:DefaultFirebaseOptions.currentPlatform); runApp(constMyApp()); }

  3. Run the following command to install the core plugin:

    flutter pub add cloud_firestore
    flutter pub add firebase_storage


  4. Once complete, rebuild your Flutter application:

    flutter run

  5. Add the following code for Adding details in your Database(Image in Firebase Storage retrieve the URL to save it along with the details in Database )
    Code for Firestore database:
    import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_storage/firebase_storage.dart'; final incidentDetails =FirebaseFirestore.instance.collection('IncidentDetails'); // Call the incident's CollectionReference to add a new incident details incidentDetails.add({ 'incident_number': _formKey.currentState!.value['incidentnumber'], 'date_of_incident':formattedDateofIncident, 'incident_location':_formKey.currentState!.value['incidentlocation'], 'incident_priority': _formKey.currentState!.value['incidentpriority'], 'incident_type':_formKey.currentState!.value['incidenttype'], 'incident_description':_formKey.currentState!.value['incidentdescription'], 'incident_image':imageUrl, }).then((DocumentReference) { setState(() { submitMessage =true; ScaffoldMessenger.of(context).showSnackBar(const SnackBar( content:Text("Submitted Succesfully!"), backgroundColor:Colors.teal, behavior:SnackBarBehavior.floating, duration:Duration(seconds: 5), )); _formKey.currentState?.reset(); }); }).catchError((error) { ScaffoldMessenger.of(context).showSnackBar(SnackBar( content:Text('Error $error'), backgroundColor:Colors.teal, behavior:SnackBarBehavior.floating, duration:const Duration(seconds: 5), )); });

    Code for FilePicker for selecting Image from my local drive and adding it in Storage:


    //File object PlatformFile? pickedFile; //File from the local drive stored in a byte format Uint8List? file; //Variable for storing URL of image fetched from firebase storage String? imageUrl; // Variable for file List<File?> files = []; final result = await FilePicker.platform .pickFiles(allowMultiple: false, type: FileType.image); if(result==null) { return; } setState(() { pickedFile= result.files.first; file= result.files.single.bytes; }); final filename='files/${pickedFile!.name}'; //Create reference for Firebase Storage Reference ref=FirebaseStorage.instance.ref().child(filename); //Add file UploadTask uploadTask=ref.putData(file!); //Wait for the Complete Response final TaskSnapshot taskSnapshot = await uploadTask.whenComplete(() {}); //get the image url imageUrl = await taskSnapshot.ref.getDownloadURL(); //file.clear(); setState(() { });


  6. Run your project and check for file creation in Firebase.(I encountered blocked by CORS error for Firebase Storage. So I had to Update my CORS policy for Storage of my project in Google Cloud Console ) . Here is link for it Click here

0 comments:

Post a Comment

Featured Post

Invoice Portal Project Links

Web App link for Invoice Portal  Invoice Portal App lets an user view and create an Invoice. Features: View the list of Number of Invoices b...

Powered by Blogger.

Popular Posts