Home > OS >  Can't seem to get app to upload image to firebase storage from camera
Can't seem to get app to upload image to firebase storage from camera

Time:12-07

I'm trying to learn how to upload images to firebase storage after my phone takes a picture. The flutter course I was gifted with that tackled this problem is outdated and the program won't upload the image to firebase storage.

The code block that tackles uploading User data to Firebase. The line "await ref.putFile(image).onComplete;" returns an error since "onComplete" doesn't exist anymore.

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

import 'package:chat_app2/widgets/auth/auth_form.dart';
import 'package:flutter/services.dart';
import 'package:firebase_storage/firebase_storage.dart';

class AuthScreen extends StatefulWidget {
  @override
  _AuthScreenState createState() => _AuthScreenState();
}

class _AuthScreenState extends State<AuthScreen> {
  final _auth = FirebaseAuth.instance;
  var _isLoading = false;
  void _submitAuthForm(String email, String username, String password,
      File image, bool isLogin, BuildContext ctx) async {
    UserCredential authResult;
    try {
      setState(() {
        _isLoading = true;
      });
      if (isLogin) {
        authResult = await _auth.signInWithEmailAndPassword(
          email: email,
          password: password,
        );
      } else {
        authResult = await _auth.createUserWithEmailAndPassword(
          email: email,
          password: password,
        );
        
         final ref = FirebaseStorage.instance
             .ref()
             .child('user_image')
             .child(authResult.user!.uid   '.jpg');

        await ref.putFile(image).onComplete;

        await FirebaseFirestore.instance
            .collection('users')
            .doc(authResult.user!.uid)
            .set({
          'username': username,
          'email': email,
        });
      }
    } on PlatformException catch (err) {
      var message = 'An error occured, please check your credentials';
      if (err.message != null) {
        message = err.message!;
      }
      final snackBar = SnackBar(
        content: Text(message),
        backgroundColor: Theme.of(ctx).errorColor,
      );
      ScaffoldMessenger.of(ctx).showSnackBar(snackBar);
      setState(() {
        _isLoading = false;
      });
    } catch (err) {
      final snackBar = SnackBar(
        content: Text(err.toString()),
        backgroundColor: Theme.of(ctx).errorColor,
      );
      ScaffoldMessenger.of(ctx).showSnackBar(snackBar);
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).primaryColor,
      body: AuthForm(
        _submitAuthForm,
        _isLoading,
      ),
    );
  }
}

The widget that "picks" the image from the camera

// ignore_for_file: unnecessary_null_comparison

import 'dart:io';

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

class UserImagePicker extends StatefulWidget {
  UserImagePicker(this.imagePickFn);

  final void Function(File pickedImage) imagePickFn;
  @override
  _UserImagePickerState createState() => _UserImagePickerState();
}

class _UserImagePickerState extends State<UserImagePicker> {
  File? _pickedImage;

  void _pickImage() async {
    final pickedImageFile =
        await ImagePicker.pickImage(source: ImageSource.camera);
    setState(() {
      _pickedImage = pickedImageFile;
    });

    widget.imagePickFn(pickedImageFile);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        CircleAvatar(
          radius: 50,
          backgroundColor: Colors.grey,
          backgroundImage:
              _pickedImage != null ? FileImage(_pickedImage!) : null,
        ),
        TextButton.icon(
            style: TextButton.styleFrom(
              primary: Theme.of(context).primaryColor,
            ),
            onPressed: _pickImage,
            icon: Icon(Icons.image),
            label: Text('Add Image')),
      ],
    );
  }
}

Program runs fine if I remove "onComplete" from line 42. It generates user data and logs it in Firebase. The only issue is that the program doesn't appear to upload the image if I do so.

CodePudding user response:

I just solved your issue. If you need explanation, kindly go to the documentations and you will have complete understanding on how to utilize the firebase upload method. Upload Task

var uploadTask = ref.putFile(image);
var storageTaskSnapshot = await uploadTask;
String url =  await storageTaskSnapshot.ref.getDownloadURL();
  • Related