skip to Main Content

Hello everyone I need help with this , I’m trying to add a profile picture for my registred users and save the profile pic in firebase :

imported files here 

class ProfilePage extends StatefulWidget {
  @override
  _ProfilePageState createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  final User? user = FirebaseAuth.instance.currentUser;
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;
  File? _imageFile;
  String? _profileImageUrl;
  
  @override
  void initState() {
    super.initState();
    _loadProfileImage();
  }

  Future<void> _loadProfileImage() async {
    if (user != null) {
      DocumentSnapshot userDoc = await _firestore.collection('users').doc(user!.uid).get();
      if (userDoc.exists && userDoc.data() != null) {
        setState(() {
          _profileImageUrl = userDoc['profilePic'];
        });
      }
    }
  }

  Future<void> _pickImage() async {
    final pickedFile = await ImagePicker().getImage(source: ImageSource.gallery);
    if (pickedFile != null) {
      setState(() {
        _imageFile = File(pickedFile.path);
      });
      _uploadImage(_imageFile!);
    }
  }

  Future<void> _uploadImage(File imageFile) async {
    try {
      String fileName = path.basename(imageFile.path);
      Reference storageRef = FirebaseStorage.instance.ref().child('profile_pics/$fileName');
      final UploadTask uploadTask = storageRef.putFile(imageFile);
      final TaskSnapshot snapshot = await uploadTask.whenComplete(() => {});
      final String downloadUrl = await snapshot.ref.getDownloadURL();

      SharedPreferences prefs = await SharedPreferences.getInstance();
      String? userId = prefs.getString('userId');

      if (userId != null) {
        await FirebaseFirestore.instance.collection('users').doc(userId).update({
          'profilePic': downloadUrl,
        });

        setState(() {
          _profileImageUrl = downloadUrl;
        });

        print('Profile picture uploaded successfully: $downloadUrl');
      } else {
        print('User ID not found in SharedPreferences');
      }
    } catch (e) {
      print('Error uploading profile picture: $e');
    }
  }

  Future<void> _signOut(BuildContext context) async {
    await FirebaseAuth.instance.signOut();
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.remove('staySignedIn');
    await prefs.remove('email');
    await prefs.remove('password');
    Navigator.pushAndRemoveUntil(
      context,
      MaterialPageRoute(builder: (context) => LoginPage()),
      (Route<dynamic> route) => false,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(user?.displayName ?? 'Profile'),
        actions: [
          IconButton(
            icon: Icon(Icons.logout),
            onPressed: () => _signOut(context),
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            children: [
              GestureDetector(
                onTap: _pickImage,
                child: CircleAvatar(
                  radius: 50,
                  backgroundImage: _imageFile != null
                      ? FileImage(_imageFile!)
                      : _profileImageUrl != null
                          ? NetworkImage(_profileImageUrl!) as ImageProvider
                          : null,
                  child: _imageFile == null && _profileImageUrl == null
                      ? Icon(Icons.add_a_photo, size: 50)
                      : null,
                ),
              ),
              SizedBox(height: 20),
              Text(
                user?.displayName ?? 'No Name',
                style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

It seems like there is an error relied to firebase storage but only due to this page.
If somoene can help me with this I would be really greatful

Ive tried a few things with my collection directly in firebase to see if the problem was really from there but it worked well .
I also tried other techniques provided on other posts but it didn’t work.

2

Answers


  1. You can directly upload the image like the following:

    Reference storageRef = FirebaseStorage.instance.ref().child('profile_pics/$fileName');
    
    await storageRef.putFile(imageFile);
    
    String url = await storageRef.getDownloadURL();
    
    Login or Signup to reply.
  2. class StorageRepo {
      final FirebaseStorage _storage = FirebaseStorage.instance;
      final FirebaseAuth _auth = FirebaseAuth.instance;
    
      Future<String> uploadImage(
          String childName, Uint8List image, bool isPost) async {
        Reference ref =
            _storage.ref().child(childName).child(_auth.currentUser!.uid);
        UploadTask uploadTask = ref.putData(image);
        TaskSnapshot snap = await uploadTask;
        String imgUrl = await snap.ref.getDownloadURL();
        return imgUrl;
      }
    

    }
    try this

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search