i need help for this,I need to make sure that the photo saved in the storage when logging out can be brought back to the user
Published: 2024-05-03 15:46:48

import 'dart:io';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:notiday_1/Objetos/Compromissos.dart';
import 'package:notiday_1/components/carrousel.dart';
import 'package:notiday_1/conection/criausuario.dart';
import 'package:notiday_1/conection/firestore_serviço.dart';
import 'package:notiday_1/configuracoes.dart';
import 'package:notiday_1/ajuda.dart';
import 'package:notiday_1/exercicio_tela.dart';
import 'package:notiday_1/main.dart';
import 'package:notiday_1/modal_inicio.dart';
import 'package:notiday_1/storage/liga%C3%A7%C3%A3o_storage.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';

class Inicio extends StatefulWidget {
  final User user;
  const Inicio({Key? key, required this.user}) : super(key: key);

  @override
  State<Inicio> createState() => _InicioState();
}

class _InicioState extends State<Inicio> {
  final CompromissoServico servico = CompromissoServico();
  final AutenticaUser deslogar = AutenticaUser();
  String? avatarUrl; // Variável para armazenar a URL da foto selecionada

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(kToolbarHeight),
        child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.only(
              bottomRight: Radius.circular(20),
              bottomLeft: Radius.circular(20),
            ),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.3),
                spreadRadius: 1,
                blurRadius: 10,
                offset: Offset(0, 3),
              ),
            ],
          ),
          child: AppBar(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.vertical(
                bottom: Radius.circular(20),
              ),
            ),
            title: Container(
              child: Row(
                children: [
                  SizedBox(width: 120.0),
                  Text(
                    'Notiday',
                    style: TextStyle(
                      fontSize: 30,
                      color: Colors.blue,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
      endDrawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: <Widget>[
            DrawerHeader(
              decoration: BoxDecoration(
                color: Colors.blue,
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'Opções',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 24,
                    ),
                  ),
                  SizedBox(height: 20),
                  InkWell(
                    onTap: () {
                      _openGallery(context);
                    },
                    child: CircleAvatar(
                      radius: 30,
                      backgroundColor: Colors.white,
                      child: avatarUrl != null
                          ? ClipOval(
                              child: Image.network(
                                avatarUrl!, // Exibe a imagem selecionada
                                fit: BoxFit.cover,
                              ),
                            )
                          : Icon(
                              Icons.photo,
                              size: 40,
                              color: Colors.blue,
                            ),
                    ),
                  ),
                ],
              ),
            ),
            ListTile(
              title: Text('Configurações'),
              onTap: () {
                Navigator.pop(context);
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => Configuracoes(),
                  ),
                );
              },
            ),
            ListTile(
              title: Text('Ajuda'),
              onTap: () {
                Navigator.pop(context);
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => AJuda(),
                  ),
                );
              },
            ),
            ListTile(
              title: Text('Sair do App'),
              onTap: () async {
                Navigator.pop(context);
                try {
                  await FirebaseAuth.instance.signOut();
                  Navigator.pushAndRemoveUntil(
                    context,
                    MaterialPageRoute(builder: (context) => MyApp()),
                    (route) => false,
                  );
                } catch (e) {
                  print("Erro ao deslogar: $e");
                }
              },
            ),
          ],
        ),
      ),
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/bg_recuperasenha.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: StreamBuilder(
          stream: servico.conectarStreamCompromisso(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(
                child: CircularProgressIndicator(),
              );
            } else {
              if (snapshot.hasData &&
                  snapshot.data != null &&
                  snapshot.data!.docs.isNotEmpty) {
                List<Compromisso> listacompromisso = [];
                for (var doc in snapshot.data!.docs) {
                  listacompromisso.add(
                    Compromisso.fromMap(
                      doc.data(),
                    ),
                  );
                }
                return Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      height: 300,
                      child: ListView.separated(
                        itemCount: listacompromisso.length,
                        separatorBuilder: (context, index) =>
                            Divider(), // Adiciona uma linha de divisão entre cada item
                        itemBuilder: (context, index) {
                          Compromisso compromisso = listacompromisso[index];
                          return ListTile(
                            title: Text(compromisso.name),
                            subtitle: Text(compromisso.horario),
                            onTap: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => CompromissoTela(
                                    compromisso: compromisso,
                                  ),
                                ),
                              );
                            },
                          );
                        },
                      ),
                    ),
                    SizedBox(
                      height: 86,
                    ),
                    Container(
                      margin: EdgeInsets.all(2),
                      height: 120,
                      width: 400,
                      child: Maps(),
                    ),
                  ],
                );
              } else {
                return Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    Container(
                      height: 200,
                      width: 200,
                      decoration: const BoxDecoration(
                        image: DecorationImage(
                          image: AssetImage('assets/Não.png'),
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),
                  ],
                );
              }
            }
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          mostrarModalInicio(context);
        },
        backgroundColor: Color.fromARGB(255, 243, 166, 0),
        foregroundColor: Colors.black,
        child: Icon(Icons.add),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
    );
  }

  Future<void> _openGallery(BuildContext context) async {
    try {
      final XFile? image =
          await ImagePicker().pickImage(source: ImageSource.gallery);
      if (image != null) {
        String? imageUrl = await uploadImageToFirebaseStorage(
            File(image.path), widget.user.uid);
        if (imageUrl != null) {
          setState(() {
            avatarUrl =
                imageUrl; // Atualiza o avatarUrl com a URL da imagem no Firebase Storage
          });
        } else {
          print('Falha ao fazer upload da imagem para o Firebase Storage.');
        }
      } else {
        // O usuário cancelou a seleção da imagem
        print('Seleção de imagem cancelada.');
      }
    } catch (e) {
      print("Erro ao abrir a galeria: $e");
    }
  }

 Future<String?> uploadImageToFirebaseStorage(
    File imageFile, String userId) async {
  try {
    // Crie uma referência para o local onde a imagem será armazenada no Firebase Storage
    String fileName =
        'profile_images/$userId/${DateTime.now().millisecondsSinceEpoch}.png';
    Reference storageRef = FirebaseStorage.instance.ref().child(fileName);

    // Faça o upload da imagem para o Firebase Storage
    UploadTask uploadTask = storageRef.putFile(imageFile);

    // Aguarde a conclusão do upload
    TaskSnapshot snapshot = await uploadTask;

    // Verifique se o upload foi concluído com sucesso
    if (snapshot.state == TaskState.success) {
      // Retorne a URL de download da imagem
      return await snapshot.ref.getDownloadURL();
    } else {
      // Se o upload não foi bem-sucedido, retorne null
      print('Erro ao fazer upload da imagem para o Firebase Storage.');
      return null;
    }
  } catch (e) {
    // Se ocorrer algum erro durante o upload, registre o erro e retorne null
    print('Erro ao fazer upload da imagem para o Firebase Storage: $e');
    return null;
  }
}


  Future<void> saveImageUrlToFirestore(String userId, String imageUrl) async {
    try {
      await FirebaseFirestore.instance
          .collection('users')
          .doc(userId)
          .set({'profileImageUrl': imageUrl}, SetOptions(merge: true));
    } catch (e) {
      print('Erro ao salvar a URL da imagem no Firestore: $e');
    }
  }
Future<String?> fetchImageUrlFromFirestore(String userId) async {
  try {
    DocumentSnapshot snapshot = await FirebaseFirestore.instance
        .collection(userId)
        .doc(userId)
        .get();
    if (snapshot.exists) {
      Map<String, dynamic>? userData = snapshot.data() as Map<String, dynamic>?; // Obtém os dados do documento
      if (userData != null && userData['profileImageUrl'] != null) {
        return userData['profileImageUrl']; // Retorna o valor do campo 'profileImageUrl'
      }
    }
  } catch (e) {
    print('Erro ao recuperar a URL da imagem do Firestore: $e');
  }
  return null;
}

}