Asset-Borrowing-App / lib / Project / ProfilePage / EditProfilePage / edit_image.dart
edit_image.dart
Raw
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_application_1/Project/ProfilePage/EditProfilePage/edit_profile_page.dart';
import 'package:flutter_application_1/Project/ProfilePage/widgets/appbar_widget.dart';
import 'package:image_picker/image_picker.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import '../../utils/colors.dart';

class EditImagePage extends StatefulWidget {
  const EditImagePage({Key? key}) : super(key: key);

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

class _EditImagePageState extends State<EditImagePage> {
  File? _imageFile;
  final picker = ImagePicker();
  final _firebaseStorage = FirebaseStorage.instance;
  final _firestore = FirebaseFirestore.instance;

  Future<void> _selectImage() async {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          content: SingleChildScrollView(
            child: ListBody(
              children: <Widget>[
                const Text(
                  'Choose an option :',
                  style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 5.0),
                SizedBox(
                  height: 40,
                  child: InkWell(
                    onTap: () async {
                      final pickedFile = await picker.pickImage(
                        source: ImageSource.camera,
                      );

                      if (pickedFile != null) {
                        setState(() {
                          _imageFile = File(pickedFile.path);
                        });
                      }
                      // ignore: use_build_context_synchronously
                      Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: ((context) => const EditProfilePage())));
                    },
                    child: Row(
                      children: const [
                        Icon(Icons.camera_alt),
                        SizedBox(width: 15.0),
                        Text(
                          'Camera',
                          style: TextStyle(
                            fontSize: 20,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                // const Padding(padding: EdgeInsets.only(bottom: 15.0)),
                SizedBox(
                  height: 40,
                  child: InkWell(
                    onTap: () async {
                      final pickedFile = await picker.pickImage(
                        source: ImageSource.gallery,
                      );

                      if (pickedFile != null) {
                        setState(() {
                          _imageFile = File(pickedFile.path);
                        });
                      }

                      Navigator.of(context).pop();
                    },
                    child: Row(
                      children: const [
                        Icon(Icons.image),
                        SizedBox(width: 15.0),
                        Text(
                          'Gallery',
                          style: TextStyle(
                            fontSize: 20,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Future<String> _uploadImageToFirebase(File file) async {
    final user = FirebaseAuth.instance.currentUser;
    final fileName = user!.uid + DateTime.now().toString() + '.png';
    final Reference ref = _firebaseStorage.ref().child('user_images/$fileName');
    final UploadTask uploadTask = ref.putFile(file);
    final TaskSnapshot taskSnapshot = await uploadTask;
    final imageUrl = await taskSnapshot.ref.getDownloadURL();
    return imageUrl;
  }

  Future<void> _saveImageToFirestore(String imageUrl) async {
    final user = FirebaseAuth.instance.currentUser;
    await _firestore
        .collection('users')
        .doc(user!.uid)
        .update({'image_url': imageUrl});
  }

  Future<void> _uploadAndSaveImage() async {
    if (_imageFile == null) {
      return;
    }

    try {
      final imageUrl = await _uploadImageToFirebase(_imageFile!);
      await _saveImageToFirestore(imageUrl);
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Image uploaded successfully')),
      );
      Navigator.push(context,
          MaterialPageRoute(builder: ((context) => const EditProfilePage())));
    } catch (error) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Failed to upload image: $error')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: buildAppBar(context),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          const SizedBox(
            width: 330,
            child: Text(
              "Upload a photo of yourself",
              style: TextStyle(
                fontSize: 23,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.only(top: 20),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Center(
                    child: Align(
                      alignment: Alignment.center,
                      child: SizedBox(
                        width: 330,
                        height: 330,
                        child: InkWell(
                          onTap: _selectImage,
                          child: _imageFile != null
                              ? Image.file(
                                  _imageFile!,
                                  height: 200,
                                  width: 200,
                                  fit: BoxFit.cover,
                                )
                              : FutureBuilder(
                                  future: FirebaseStorage.instance
                                      .ref('/admin_images/blankImage.jpg')
                                      .getDownloadURL(),
                                  builder: (BuildContext context,
                                      AsyncSnapshot<String> snapshot) {
                                    if (snapshot.hasError) {
                                      return const Icon(
                                        Icons.error_outline,
                                        size: 50,
                                      );
                                    } else if (snapshot.connectionState ==
                                        ConnectionState.done) {
                                      return Image.network(
                                        snapshot.data!,
                                        height: 200,
                                        width: 200,
                                        fit: BoxFit.cover,
                                      );
                                    } else {
                                      return const CircularProgressIndicator();
                                    }
                                  },
                                ),
                        ),
                      ),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 30),
                    child: Align(
                      alignment: Alignment.bottomCenter,
                      child: SizedBox(
                        width: 330,
                        height: 50,
                        child: ElevatedButton(
                          onPressed: _uploadAndSaveImage,
                          child: const Text(
                            'Save Image',
                            style: TextStyle(fontSize: 15),
                          ),
                          style: ButtonStyle(
                            backgroundColor: MaterialStateProperty.all<Color>(
                                kGreenColor),
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}