Firebase + Flutter integration

Firebase made easy for flutter developer to manage server side APis.

Lets start with creating flutter project in firebase console.

Follow below link for how to create new project in firebase.

Goolge Firebase Setup

Once you finish with integrating firebase in flutter follow below steps for development.
How my database in firebase looks like check below,





















Step 1:
Add below dependecies inside your pubspec.yaml

  cloud_firestore: ^2.2.0
  firebase_storage: ^8.1.0















Step 2: Initialize firebase

    Firebase.initializeApp();
@override
void initState() {
// TODO: implement initState
print("init");
Firebase.initializeApp();
_accessDatabase();
super.initState();
}
  
 
 Step 3: Start writing insert, update, delete functions of firebase.
 
 Future<List<Product>> getProduct(
    String categoryId, String subCategoryId) async {
List<Product> productList = new List<Product>();

await FirebaseFirestore.instance
.collection("Product")
.where('category_id', isEqualTo: categoryId)
.where('sub_category_id', isEqualTo: subCategoryId)
.get()
.then((value) async {
productList.clear();
await value.docs.forEach((element) {
productList.add(new Product.fromJson(element.id, element.data()));
});
});
return productList;
}
 
 Future<void> addProduct(Product product) async {
  await FirebaseFirestore.instance
.collection("Product")
.add(product.toJson())
.then((value) async {
value.get().then((value) {});
});
}

Future<void> deleteProduct(String productId) async {
await FirebaseFirestore.instance
.collection("Product")
.doc(productId)
.delete();
}
  
  
  
 Now call this methods in initState

 Future<void> _accessDatabase() async {

    await _getProducts("cat1","subcat1");
  }
  
Future<List<Product>> _getProducts(SubCategory subCategory) async {
await myFireStore
.getProduct(subCategory.category_id, subCategory.id)
.then((value) {
if (value.length > 0) {
setState(() {
products = value;
});
}
});
return products;
}
  @override
void initState() {
// TODO: implement initState
print("init");
Firebase.initializeApp();
_accessDatabase();
super.initState();
}


for add query try below code.

TextButton(
            child: Text('Add'),
            onPressed: () {
              String name = txtProductName.text.toString();
        String desc = txtProductDesc.text.toString();
        String price = txtPrice.text.toString();
        Product product = new Product();
        if (!name.isEmpty && !desc.isEmpty && !price.isEmpty) {
        product.name = name;
        product.description = desc;
        product.price = price;
                 addProduct(product);
  ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text("product Added"),
));
Navigator.of(context).pop();
}
            },
          ),
  

Upload Image on FireStore:
  
You can also upload image to firebase using following code.
For this you need firebase storage like below,








Future<String> uploadImageToFirebase(
BuildContext context, File imageFile) async {
String imageUrl = "";
String fileName = basename(imageFile.path);
Reference firebaseStorageRef =
FirebaseStorage.instance.ref().child('uploads/$fileName');
UploadTask uploadTask = firebaseStorageRef.putFile(imageFile);
await uploadTask.whenComplete(() async {
await firebaseStorageRef.getDownloadURL().then((value) async {
imageUrl = value;
});
});
return imageUrl;
}
  
Future<String> getImageURL(String url) async {
final ref = FirebaseStorage.instance.ref().child('upload');
return await ref.getDownloadURL();
}

  inside your UI part add below,
  
   imgFromGallery(BuildContext context) async {
  var pickFile = await ImagePicker()
.getImage(source: ImageSource.gallery, imageQuality: 10);

if (pickFile != null) {
_image = File(pickFile.path);
await myFireStore.uploadImageToFirebase(context, _image).then((value) {
setState(() {
_imageUrl = value;
});
});
} else {
print('No image selected.');
}
}





Comments

Popular posts from this blog

Flutter Bloc Pattern 8.0.0 Call API

Learn SQLite using flutter

Search by character in flutter