tudo sobre a memoria da ia, formatação, memória e conhecimento de pdfs, junto da inserção de pdfs
This commit is contained in:
@@ -327,13 +327,19 @@ class _TutorChatPageState extends State<TutorChatPage>
|
||||
|
||||
void _addWelcomeMessage() {
|
||||
final welcomeMessage = {
|
||||
'content': '''Olá! Sou seu assistente educacional AI. Posso ajudar você a:
|
||||
'content': '''**Olá! Sou o GOAT, o teu Assistente IA oficial do Teach it.** 🐐
|
||||
|
||||
📚 **Explicar conceitos** de forma detalhada
|
||||
🤔 **Fazer perguntas socráticas** para guiar seu aprendizado
|
||||
🔍 **Explorar tópicos** de forma interativa
|
||||
Estou aqui para te ajudar a aprender de forma confiante e motivadora!
|
||||
|
||||
Escolha um modo de tutoria e faça sua pergunta sobre o conteúdo disponível!''',
|
||||
**O que posso fazer por ti:**
|
||||
📚 **Explicar conceitos** usando o material do teu professor
|
||||
🤔 **Fazer perguntas socráticas** para guiar tua aprendizagem
|
||||
🔍 **Explorar tópicos** de forma interativa com os PDFs disponibilizados
|
||||
🎯 **Adaptar-me** ao método de ensino do teu professor
|
||||
|
||||
Escolhe um modo de tutoria e envia a tua pergunta sobre qualquer assunto educacional!
|
||||
|
||||
**Estou pronto quando tu estiveres!** 💪''',
|
||||
'isUser': false,
|
||||
'timestamp': DateTime.now(),
|
||||
'sources': <SourceCitation>[],
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_animate/flutter_animate.dart';
|
||||
import 'package:flutter_markdown/flutter_markdown.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import '../../../../core/services/auth_service.dart';
|
||||
import '../../../../core/services/rag_ai_service.dart';
|
||||
import '../../../../core/utils/logger.dart';
|
||||
|
||||
/// Simple AI Tutor chat interface page (for testing)
|
||||
class TutorChatPageSimple extends StatefulWidget {
|
||||
@@ -193,19 +194,43 @@ class _TutorChatPageSimpleState extends State<TutorChatPageSimple>
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Text(
|
||||
content,
|
||||
style: TextStyle(
|
||||
color: isUser
|
||||
? Colors.white
|
||||
: const Color(0xFF2D3748),
|
||||
fontSize: 16,
|
||||
height: 1.4,
|
||||
fontWeight: isUser
|
||||
? FontWeight.w500
|
||||
: FontWeight.normal,
|
||||
),
|
||||
),
|
||||
child: isUser
|
||||
? Text(
|
||||
content,
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 16,
|
||||
height: 1.4,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
)
|
||||
: MarkdownBody(
|
||||
data: content,
|
||||
styleSheet: MarkdownStyleSheet(
|
||||
p: TextStyle(
|
||||
color: const Color(0xFF2D3748),
|
||||
fontSize: 16,
|
||||
height: 1.4,
|
||||
),
|
||||
strong: TextStyle(
|
||||
color: const Color(0xFF2D3748),
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
height: 1.4,
|
||||
),
|
||||
em: TextStyle(
|
||||
color: const Color(0xFF2D3748),
|
||||
fontSize: 16,
|
||||
fontStyle: FontStyle.italic,
|
||||
height: 1.4,
|
||||
),
|
||||
listBullet: TextStyle(
|
||||
color: const Color(0xFF2D3748),
|
||||
fontSize: 16,
|
||||
height: 1.4,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (isUser) ...[
|
||||
@@ -373,20 +398,20 @@ class _TutorChatPageSimpleState extends State<TutorChatPageSimple>
|
||||
|
||||
void _addWelcomeMessage() {
|
||||
final welcomeMessage = {
|
||||
'content': '''Olá! Sou seu assistente educacional AI.
|
||||
'content': '''**Olá! Sou o GOAT, o teu Assistente IA oficial do Teach it.** 🐐
|
||||
|
||||
Bem-vindo ao TeachIT AI Tutor!
|
||||
Estou aqui para te ajudar a aprender de forma confiante e motivadora!
|
||||
|
||||
Funcionalidades disponíveis:
|
||||
📚 Respostas baseadas em conteúdo educacional
|
||||
🔍 Busca vetorial semântica
|
||||
🤖 Integração com Ollama API
|
||||
📖 Citações de fontes relevantes
|
||||
🎯 Modo de aprendizado adaptativo
|
||||
**O que posso fazer por ti:**
|
||||
📚 Responder com base no material do teu professor
|
||||
🔍 Usar os PDFs e documentos disponibilizados
|
||||
<EFBFBD> Explicar conceitos de forma clara e organizada
|
||||
🎯 Adaptar-me ao método de ensino do teu professor
|
||||
|
||||
O sistema usa RAG (Retrieval-Augmented Generation) para fornecer respostas baseadas apenas no conteúdo educacional disponível.
|
||||
**Como funciona:**
|
||||
Envia-me a tua pergunta sobre qualquer assunto educacional e vou usar o material disponível para te dar a melhor resposta possível.
|
||||
|
||||
Faça sua pergunta sobre qualquer assunto educacional!''',
|
||||
**Estou pronto quando tu estiveres!** 💪''',
|
||||
'isUser': false,
|
||||
'timestamp': DateTime.now(),
|
||||
};
|
||||
@@ -419,53 +444,28 @@ Faça sua pergunta sobre qualquer assunto educacional!''',
|
||||
_scrollToBottom();
|
||||
|
||||
try {
|
||||
// Direct call to Ollama API based on working example
|
||||
print('Processing query: $userMessage');
|
||||
// Use RAGAIService with memory, PDFs, and O GOAT identity
|
||||
Logger.info('USING RAG AI SERVICE');
|
||||
|
||||
final url = Uri.parse('http://89.114.196.110:11434/api/chat');
|
||||
final replyText = await RAGAIService.ask(userMessage);
|
||||
|
||||
final response = await http
|
||||
.post(
|
||||
url,
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: jsonEncode({
|
||||
'model': 'qwen3-coder:30b',
|
||||
'messages': [
|
||||
{'role': 'user', 'content': userMessage},
|
||||
],
|
||||
'stream': false,
|
||||
}),
|
||||
)
|
||||
.timeout(const Duration(seconds: 60));
|
||||
final preview = replyText.length > 50
|
||||
? replyText.substring(0, 50)
|
||||
: replyText;
|
||||
Logger.info('Ollama response received: $preview...');
|
||||
|
||||
print('API response status: ${response.statusCode}');
|
||||
print('API response body: ${response.body}');
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = jsonDecode(response.body);
|
||||
final replyText = data['message']?['content'] ?? 'Sem resposta.';
|
||||
|
||||
final preview = replyText.length > 50
|
||||
? replyText.substring(0, 50)
|
||||
: replyText;
|
||||
print('Ollama response received: $preview...');
|
||||
|
||||
setState(() {
|
||||
_messages.add({
|
||||
'content': replyText,
|
||||
'isUser': false,
|
||||
'timestamp': DateTime.now(),
|
||||
});
|
||||
_isLoading = false;
|
||||
setState(() {
|
||||
_messages.add({
|
||||
'content': replyText,
|
||||
'isUser': false,
|
||||
'timestamp': DateTime.now(),
|
||||
});
|
||||
} else {
|
||||
throw Exception('Erro HTTP ${response.statusCode}');
|
||||
}
|
||||
_isLoading = false;
|
||||
});
|
||||
} catch (e) {
|
||||
// Fallback to mock response if API fails
|
||||
print('Ollama API error: $e');
|
||||
print('Stack trace: ${StackTrace.current}');
|
||||
final aiResponse = _generateMockResponse(userMessage);
|
||||
// Fallback to error message if API fails
|
||||
Logger.error('RAG AI Service error: $e');
|
||||
final aiResponse = 'Desculpe, ocorreu um erro ao processar a pergunta. Tente novamente.';
|
||||
|
||||
setState(() {
|
||||
_messages.add({
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_animate/flutter_animate.dart';
|
||||
import 'package:flutter_markdown/flutter_markdown.dart';
|
||||
import '../../../../core/services/rag_service.dart';
|
||||
|
||||
/// Widget for displaying chat messages with source citations
|
||||
@@ -139,15 +140,43 @@ class MessageBubble extends StatelessWidget {
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
content,
|
||||
style: TextStyle(
|
||||
color: isUser ? Colors.white : const Color(0xFF2D3748),
|
||||
fontSize: 16,
|
||||
height: 1.4,
|
||||
fontWeight: isUser ? FontWeight.w500 : FontWeight.normal,
|
||||
),
|
||||
),
|
||||
isUser
|
||||
? Text(
|
||||
content,
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 16,
|
||||
height: 1.4,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
)
|
||||
: MarkdownBody(
|
||||
data: content,
|
||||
styleSheet: MarkdownStyleSheet(
|
||||
p: TextStyle(
|
||||
color: const Color(0xFF2D3748),
|
||||
fontSize: 16,
|
||||
height: 1.4,
|
||||
),
|
||||
strong: TextStyle(
|
||||
color: const Color(0xFF2D3748),
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
height: 1.4,
|
||||
),
|
||||
em: TextStyle(
|
||||
color: const Color(0xFF2D3748),
|
||||
fontSize: 16,
|
||||
fontStyle: FontStyle.italic,
|
||||
height: 1.4,
|
||||
),
|
||||
listBullet: TextStyle(
|
||||
color: const Color(0xFF2D3748),
|
||||
fontSize: 16,
|
||||
height: 1.4,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
@@ -6,6 +6,7 @@ import 'package:flutter_animate/flutter_animate.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../../../core/services/auth_service.dart';
|
||||
import '../../../../features/materials/presentation/pages/teacher_materials_page.dart';
|
||||
|
||||
/// Quick access cards for teacher actions
|
||||
class TeacherQuickActionsWidget extends StatefulWidget {
|
||||
@@ -90,7 +91,12 @@ class _TeacherQuickActionsWidgetState extends State<TeacherQuickActionsWidget> {
|
||||
color: Colors.transparent,
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
onTap: () => context.go('/teacher/upload'),
|
||||
onTap: () => Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (_) => const TeacherMaterialsPage(),
|
||||
),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Column(
|
||||
|
||||
@@ -0,0 +1,572 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cloud_firestore/cloud_firestore.dart';
|
||||
import 'package:file_selector/file_selector.dart';
|
||||
import 'package:firebase_auth/firebase_auth.dart';
|
||||
import 'package:firebase_storage/firebase_storage.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:image_picker/image_picker.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:path/path.dart' as path;
|
||||
|
||||
import '../../../../core/services/auth_service.dart';
|
||||
|
||||
/// Página de Materiais do Professor
|
||||
/// Tela dedicada para upload e gestão de materiais para a IA
|
||||
class TeacherMaterialsPage extends StatefulWidget {
|
||||
const TeacherMaterialsPage({super.key});
|
||||
|
||||
@override
|
||||
State<TeacherMaterialsPage> createState() => _TeacherMaterialsPageState();
|
||||
}
|
||||
|
||||
class _TeacherMaterialsPageState extends State<TeacherMaterialsPage> {
|
||||
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
|
||||
final FirebaseStorage _storage = FirebaseStorage.instanceFor(
|
||||
bucket: 'teachit-app.firebasestorage.app',
|
||||
);
|
||||
final ImagePicker _imagePicker = ImagePicker();
|
||||
bool _isUploading = false;
|
||||
|
||||
Stream<QuerySnapshot> _getMaterialsStream() {
|
||||
final currentUser = AuthService.currentUser;
|
||||
if (currentUser == null) {
|
||||
return const Stream.empty();
|
||||
}
|
||||
|
||||
return _firestore
|
||||
.collection('materials')
|
||||
.where('teacherId', isEqualTo: currentUser.uid)
|
||||
.orderBy('createdAt', descending: true)
|
||||
.snapshots();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text(
|
||||
'Materiais da Turma',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
backgroundColor: const Color(0xFF82C9BD),
|
||||
elevation: 0,
|
||||
iconTheme: const IconThemeData(color: Colors.white),
|
||||
),
|
||||
floatingActionButton: _isUploading
|
||||
? FloatingActionButton.extended(
|
||||
onPressed: null,
|
||||
backgroundColor: const Color(0xFFF68D2D).withOpacity(0.6),
|
||||
icon: const SizedBox(
|
||||
width: 20,
|
||||
height: 20,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
label: const Text(
|
||||
'A enviar...',
|
||||
style: TextStyle(color: Colors.white),
|
||||
),
|
||||
)
|
||||
: FloatingActionButton.extended(
|
||||
onPressed: _showUploadOptions,
|
||||
backgroundColor: const Color(0xFFF68D2D),
|
||||
icon: const Icon(Icons.add, color: Colors.white),
|
||||
label: const Text(
|
||||
'Adicionar',
|
||||
style: TextStyle(color: Colors.white),
|
||||
),
|
||||
),
|
||||
|
||||
body: Container(
|
||||
decoration: const BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: [
|
||||
Color(0xFF82C9BD),
|
||||
Color(0xFFF8F9FA),
|
||||
],
|
||||
stops: [0.0, 0.4],
|
||||
),
|
||||
),
|
||||
child: SafeArea(
|
||||
child: StreamBuilder<QuerySnapshot>(
|
||||
stream: _getMaterialsStream(),
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.connectionState == ConnectionState.waiting) {
|
||||
return const Center(
|
||||
child: CircularProgressIndicator(
|
||||
color: Color(0xFF82C9BD),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (snapshot.hasError) {
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.error_outline,
|
||||
color: Colors.red,
|
||||
size: 48,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Erro ao carregar materiais:\n${snapshot.error}',
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(
|
||||
color: Color(0xFF2D3748),
|
||||
fontSize: 16,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final materials = snapshot.data?.docs ?? [];
|
||||
|
||||
if (materials.isEmpty) {
|
||||
return const Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.folder_open,
|
||||
color: Color(0xFF718096),
|
||||
size: 64,
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
Text(
|
||||
'Nenhum material enviado ainda.',
|
||||
style: TextStyle(
|
||||
color: Color(0xFF718096),
|
||||
fontSize: 16,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 8),
|
||||
Text(
|
||||
'Os materiais enviados aparecerão aqui.',
|
||||
style: TextStyle(
|
||||
color: Color(0xFF9CA3AF),
|
||||
fontSize: 14,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return ListView.builder(
|
||||
padding: const EdgeInsets.all(16),
|
||||
itemCount: materials.length,
|
||||
itemBuilder: (context, index) {
|
||||
final material = materials[index].data() as Map<String, dynamic>;
|
||||
final fileName = material['fileName'] ?? 'Ficheiro sem nome';
|
||||
final createdAt = material['createdAt'] as Timestamp?;
|
||||
// Inferir tipo pela extensão do filename
|
||||
final extension = path.extension(fileName).toLowerCase();
|
||||
final fileType = extension == '.pdf' ? 'pdf' :
|
||||
(extension == '.jpg' || extension == '.jpeg' || extension == '.png') ? 'image' : 'other';
|
||||
|
||||
return _buildMaterialCard(
|
||||
fileName: fileName,
|
||||
fileType: fileType,
|
||||
createdAt: createdAt,
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _showUploadOptions() {
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
backgroundColor: Colors.transparent,
|
||||
builder: (context) => Container(
|
||||
decoration: const BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.vertical(
|
||||
top: Radius.circular(20),
|
||||
),
|
||||
),
|
||||
child: SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Center(
|
||||
child: Container(
|
||||
width: 40,
|
||||
height: 4,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.grey[300],
|
||||
borderRadius: BorderRadius.circular(2),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
const Text(
|
||||
'Adicionar Material',
|
||||
style: TextStyle(
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Color(0xFF2D3748),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
_buildUploadOption(
|
||||
icon: Icons.picture_as_pdf,
|
||||
color: Colors.red,
|
||||
title: 'PDF',
|
||||
subtitle: 'Selecionar ficheiro PDF',
|
||||
onTap: () {
|
||||
Navigator.pop(context);
|
||||
_selectPDF();
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_buildUploadOption(
|
||||
icon: Icons.image,
|
||||
color: Colors.blue,
|
||||
title: 'Imagem da Galeria',
|
||||
subtitle: 'Escolher foto existente',
|
||||
onTap: () {
|
||||
Navigator.pop(context);
|
||||
_selectImageFromGallery();
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_buildUploadOption(
|
||||
icon: Icons.camera_alt,
|
||||
color: const Color(0xFF82C9BD),
|
||||
title: 'Foto da Câmara',
|
||||
subtitle: 'Tirar foto nova',
|
||||
onTap: () {
|
||||
Navigator.pop(context);
|
||||
_takePhotoWithCamera();
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildUploadOption({
|
||||
required IconData icon,
|
||||
required Color color,
|
||||
required String title,
|
||||
required String subtitle,
|
||||
required VoidCallback onTap,
|
||||
}) {
|
||||
return InkWell(
|
||||
onTap: onTap,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(0.05),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: color.withOpacity(0.2),
|
||||
width: 1,
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 48,
|
||||
height: 48,
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Icon(
|
||||
icon,
|
||||
color: color,
|
||||
size: 24,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
title,
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Color(0xFF2D3748),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
subtitle,
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
color: Colors.grey[600],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Icon(
|
||||
Icons.arrow_forward_ios,
|
||||
color: Colors.grey[400],
|
||||
size: 16,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _selectPDF() async {
|
||||
try {
|
||||
const XTypeGroup pdfTypeGroup = XTypeGroup(
|
||||
label: 'PDFs',
|
||||
extensions: ['pdf'],
|
||||
uniformTypeIdentifiers: ['com.adobe.pdf'],
|
||||
);
|
||||
|
||||
final XFile? file = await openFile(acceptedTypeGroups: [pdfTypeGroup]);
|
||||
if (file == null) return;
|
||||
|
||||
await _uploadFile(
|
||||
filePath: file.path,
|
||||
fileName: path.basename(file.path),
|
||||
fileType: 'pdf',
|
||||
);
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
_showErrorSnackBar('Erro ao selecionar PDF: $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _selectImageFromGallery() async {
|
||||
try {
|
||||
final XFile? image = await _imagePicker.pickImage(
|
||||
source: ImageSource.gallery,
|
||||
maxWidth: 1920,
|
||||
maxHeight: 1080,
|
||||
imageQuality: 85,
|
||||
);
|
||||
if (image == null) return;
|
||||
|
||||
await _uploadFile(
|
||||
filePath: image.path,
|
||||
fileName: path.basename(image.path),
|
||||
fileType: 'image',
|
||||
);
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
_showErrorSnackBar('Erro ao selecionar imagem: $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _takePhotoWithCamera() async {
|
||||
try {
|
||||
final XFile? photo = await _imagePicker.pickImage(
|
||||
source: ImageSource.camera,
|
||||
maxWidth: 1920,
|
||||
maxHeight: 1080,
|
||||
imageQuality: 85,
|
||||
);
|
||||
if (photo == null) return;
|
||||
|
||||
await _uploadFile(
|
||||
filePath: photo.path,
|
||||
fileName: path.basename(photo.path),
|
||||
fileType: 'image',
|
||||
);
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
_showErrorSnackBar('Erro ao tirar foto: $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _uploadFile({
|
||||
required String filePath,
|
||||
required String fileName,
|
||||
required String fileType,
|
||||
}) async {
|
||||
final currentUser = FirebaseAuth.instance.currentUser;
|
||||
if (currentUser == null) {
|
||||
_showErrorSnackBar('Utilizador não autenticado');
|
||||
return;
|
||||
}
|
||||
|
||||
final uid = currentUser.uid;
|
||||
final cleanFileName = path.basename(fileName);
|
||||
|
||||
setState(() => _isUploading = true);
|
||||
|
||||
try {
|
||||
// Upload para Firebase Storage: teachers/{uid}/materials/{fileName}
|
||||
final storage = FirebaseStorage.instanceFor(
|
||||
bucket: 'teachit-app.firebasestorage.app',
|
||||
);
|
||||
final ref = storage
|
||||
.ref()
|
||||
.child('teachers')
|
||||
.child(uid)
|
||||
.child('materials')
|
||||
.child(cleanFileName);
|
||||
|
||||
await ref.putFile(File(filePath));
|
||||
final downloadUrl = await ref.getDownloadURL();
|
||||
|
||||
// Criar documento no Firestore
|
||||
await FirebaseFirestore.instance.collection('materials').add({
|
||||
'teacherId': uid,
|
||||
'fileName': cleanFileName,
|
||||
'url': downloadUrl,
|
||||
'createdAt': FieldValue.serverTimestamp(),
|
||||
});
|
||||
|
||||
if (mounted) {
|
||||
_showSuccessSnackBar('Material enviado com sucesso!');
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
_showErrorSnackBar('Erro ao enviar material: $e');
|
||||
}
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() => _isUploading = false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _showSuccessSnackBar(String message) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Row(
|
||||
children: [
|
||||
const Icon(Icons.check_circle, color: Colors.white),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: Text(message)),
|
||||
],
|
||||
),
|
||||
backgroundColor: const Color(0xFF10B981),
|
||||
behavior: SnackBarBehavior.floating,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||
duration: const Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _showErrorSnackBar(String message) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Row(
|
||||
children: [
|
||||
const Icon(Icons.error_outline, color: Colors.white),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: Text(message)),
|
||||
],
|
||||
),
|
||||
backgroundColor: Colors.red,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||
duration: const Duration(seconds: 3),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildMaterialCard({
|
||||
required String fileName,
|
||||
required String fileType,
|
||||
required Timestamp? createdAt,
|
||||
}) {
|
||||
IconData iconData;
|
||||
Color iconColor;
|
||||
|
||||
switch (fileType.toLowerCase()) {
|
||||
case 'pdf':
|
||||
iconData = Icons.picture_as_pdf;
|
||||
iconColor = Colors.red;
|
||||
break;
|
||||
case 'image':
|
||||
case 'jpg':
|
||||
case 'jpeg':
|
||||
case 'png':
|
||||
iconData = Icons.image;
|
||||
iconColor = Colors.blue;
|
||||
break;
|
||||
default:
|
||||
iconData = Icons.insert_drive_file;
|
||||
iconColor = const Color(0xFF82C9BD);
|
||||
}
|
||||
|
||||
String formattedDate = 'Data desconhecida';
|
||||
if (createdAt != null) {
|
||||
formattedDate = DateFormat('dd/MM/yyyy HH:mm').format(createdAt.toDate());
|
||||
}
|
||||
|
||||
return Card(
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
elevation: 2,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: ListTile(
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 12,
|
||||
),
|
||||
leading: Container(
|
||||
width: 48,
|
||||
height: 48,
|
||||
decoration: BoxDecoration(
|
||||
color: iconColor.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Icon(
|
||||
iconData,
|
||||
color: iconColor,
|
||||
size: 28,
|
||||
),
|
||||
),
|
||||
title: Text(
|
||||
fileName,
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.w600,
|
||||
fontSize: 16,
|
||||
color: Color(0xFF2D3748),
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
subtitle: Text(
|
||||
formattedDate,
|
||||
style: const TextStyle(
|
||||
color: Color(0xFF718096),
|
||||
fontSize: 13,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user