add signature module for all

This commit is contained in:
ALim Aidrus 2025-11-15 21:36:42 +08:00
parent 882386c522
commit eafa08b28c
4 changed files with 238 additions and 4 deletions

View File

@ -1,9 +1,11 @@
import 'dart:io'; import 'dart:io';
import 'dart:typed_data'; // <-- ADDED IMPORT
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import 'package:image_picker/image_picker.dart'; import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart'; import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as p; import 'package:path/path.dart' as p;
import 'package:signature/signature.dart'; // <-- ADDED IMPORT
import 'package:environment_monitoring_app/auth_provider.dart'; import 'package:environment_monitoring_app/auth_provider.dart';
import 'package:environment_monitoring_app/services/api_service.dart'; import 'package:environment_monitoring_app/services/api_service.dart';
@ -20,10 +22,19 @@ class _ProfileScreenState extends State<ProfileScreen> {
bool _isLoading = false; bool _isLoading = false;
String _errorMessage = ''; String _errorMessage = '';
File? _profileImageFile; File? _profileImageFile;
File? _signatureImageFile; // <-- ADDED STATE VARIABLE
// FIX: Use late initialization to retrieve the service instance. // FIX: Use late initialization to retrieve the service instance.
late ApiService _apiService; late ApiService _apiService;
// --- ADDED SIGNATURE CONTROLLER ---
final SignatureController _signatureController = SignatureController(
penStrokeWidth: 3,
penColor: Colors.black,
exportBackgroundColor: Colors.transparent, // For transparent PNG
);
// --- END OF CONTROLLER ---
@override @override
void initState() { void initState() {
super.initState(); super.initState();
@ -32,10 +43,14 @@ class _ProfileScreenState extends State<ProfileScreen> {
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
_apiService = Provider.of<ApiService>(context, listen: false); _apiService = Provider.of<ApiService>(context, listen: false);
_loadLocalProfileImage().then((_) { _loadLocalProfileImage().then((_) {
// If no profile data is available at all, trigger a refresh // --- MODIFIED: Chain signature loading ---
if (Provider.of<AuthProvider>(context, listen: false).profileData == null) { _loadLocalSignatureImage().then((_) {
_refreshProfile(); // If no profile data is available at all, trigger a refresh
} if (Provider.of<AuthProvider>(context, listen: false).profileData == null) {
_refreshProfile();
}
});
// --- END MODIFIED ---
}); });
}); });
} }
@ -53,6 +68,7 @@ class _ProfileScreenState extends State<ProfileScreen> {
await auth.refreshProfile(); await auth.refreshProfile();
// After syncing, reload the potentially new profile image // After syncing, reload the potentially new profile image
await _loadLocalProfileImage(); await _loadLocalProfileImage();
await _loadLocalSignatureImage(); // <-- ADDED THIS LINE
} catch (e) { } catch (e) {
if (mounted) { if (mounted) {
setState(() { setState(() {
@ -94,6 +110,36 @@ class _ProfileScreenState extends State<ProfileScreen> {
} }
} }
// --- ADDED NEW FUNCTION ---
/// Loads the signature image from the local cache or downloads it if not present.
Future<void> _loadLocalSignatureImage() async {
final auth = Provider.of<AuthProvider>(context, listen: false);
// Assumes the field name in your DB/profile JSON is 'signature_path'
final String? serverSignaturePath = auth.profileData?['signature_path'];
if (serverSignaturePath != null && serverSignaturePath.isNotEmpty) {
final String localFileName = p.basename(serverSignaturePath);
final Directory appDocDir = await getApplicationDocumentsDirectory();
// Store signatures in their own sub-directory
final String localFilePath = p.join(appDocDir.path, 'signatures', localFileName);
final File localFile = File(localFilePath);
if (await localFile.exists()) {
if (mounted) setState(() => _signatureImageFile = localFile);
} else {
final String fullImageUrl = ApiService.imageBaseUrl + serverSignaturePath;
// We can re-use the downloadProfilePicture method, just provide a different local path
final downloadedFile = await _apiService.downloadProfilePicture(fullImageUrl, localFilePath);
if (downloadedFile != null && mounted) {
setState(() => _signatureImageFile = downloadedFile);
}
}
} else {
if (mounted) setState(() => _signatureImageFile = null);
}
}
// --- END OF NEW FUNCTION ---
/// Shows a modal bottom sheet for selecting an image source. /// Shows a modal bottom sheet for selecting an image source.
Future<void> _showImageSourceSelection() async { Future<void> _showImageSourceSelection() async {
showModalBottomSheet( showModalBottomSheet(
@ -154,6 +200,106 @@ class _ProfileScreenState extends State<ProfileScreen> {
} }
} }
// --- ADDED THESE 2 NEW FUNCTIONS ---
/// Shows the signature pad dialog.
Future<void> _showSignaturePad() async {
_signatureController.clear(); // Clear any previous drawings
final File? signatureFile = await showDialog<File?>(
context: context,
barrierDismissible: false,
builder: (BuildContext dialogContext) {
return AlertDialog(
title: const Text("Provide Your Signature"),
content: Container(
width: double.maxFinite,
height: 300,
decoration: BoxDecoration(
border: Border.all(color: Colors.grey.shade400),
color: Colors.grey.shade200, // Background for the pad
),
child: Signature(
controller: _signatureController,
backgroundColor: Colors.white,
),
),
actions: <Widget>[
TextButton(
child: const Text("Clear"),
onPressed: () {
_signatureController.clear();
},
),
TextButton(
child: const Text("Cancel"),
onPressed: () {
Navigator.pop(dialogContext, null);
},
),
ElevatedButton(
child: const Text("Save"),
onPressed: () async {
if (_signatureController.isNotEmpty) {
final Uint8List? data = await _signatureController.toPngBytes();
if (data != null) {
final tempDir = await getTemporaryDirectory();
final file = File(p.join(tempDir.path, "signature_${DateTime.now().millisecondsSinceEpoch}.png"));
await file.writeAsBytes(data);
Navigator.pop(dialogContext, file);
}
} else {
// Show a snackbar if the signature is empty
ScaffoldMessenger.of(dialogContext).showSnackBar(
const SnackBar(
content: Text("Please provide a signature first."),
duration: Duration(seconds: 2),
),
);
}
},
),
],
);
},
);
// After dialog is closed, check if we got a file
if (signatureFile != null) {
await _uploadSignature(signatureFile);
}
}
/// Uploads the signature file and refreshes the profile.
Future<void> _uploadSignature(File signatureFile) async {
setState(() => _isLoading = true);
final uploadResult = await _apiService.uploadSignature(signatureFile);
if (mounted) {
if (uploadResult['success']) {
// Refresh profile to get new signature_path and display it
await _refreshProfile();
_showSnackBar("Signature updated successfully.", isError: false);
} else {
setState(() {
_errorMessage = uploadResult['message'] ?? 'Failed to upload signature.';
});
_showSnackBar(_errorMessage, isError: true);
}
setState(() => _isLoading = false);
}
// Clean up temp file
try {
if (await signatureFile.exists()) {
await signatureFile.delete();
}
} catch (e) {
debugPrint("Error deleting temp signature file: $e");
}
}
// --- END OF NEW FUNCTIONS ---
void _showSnackBar(String message, {bool isError = false}) { void _showSnackBar(String message, {bool isError = false}) {
if (mounted) { if (mounted) {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
@ -260,6 +406,12 @@ class _ProfileScreenState extends State<ProfileScreen> {
_buildProfileDetail(context, "Position:", profileData['position_name']), _buildProfileDetail(context, "Position:", profileData['position_name']),
]), ]),
const SizedBox(height: 24), const SizedBox(height: 24),
// --- ADDED THIS SECTION ---
_buildSignatureSection(context),
const SizedBox(height: 24),
// --- END OF ADDED SECTION ---
_buildProfileSection(context, "Account Status", [ _buildProfileSection(context, "Account Status", [
_buildProfileDetail(context, "Account Status:", profileData['account_status']), _buildProfileDetail(context, "Account Status:", profileData['account_status']),
_buildProfileDetail(context, "Registered On:", profileData['date_registered']), _buildProfileDetail(context, "Registered On:", profileData['date_registered']),
@ -338,6 +490,65 @@ class _ProfileScreenState extends State<ProfileScreen> {
); );
} }
// --- ADDED NEW WIDGET METHOD ---
Widget _buildSignatureSection(BuildContext context) {
return Card(
elevation: 4,
margin: const EdgeInsets.symmetric(vertical: 8.0),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Signature",
style: Theme.of(context).textTheme.headlineSmall?.copyWith(fontWeight: FontWeight.bold, color: Theme.of(context).primaryColor),
),
const Divider(height: 20, thickness: 1.5),
Center(
child: Container(
width: double.infinity,
height: 150,
decoration: BoxDecoration(
color: Colors.grey.shade200,
border: Border.all(color: Colors.grey.shade400),
borderRadius: BorderRadius.circular(8),
),
child: Padding(
padding: const EdgeInsets.all(4.0),
child: _signatureImageFile != null
? Image.file(
_signatureImageFile!,
fit: BoxFit.contain,
)
: Center(
child: Text(
"No signature set.",
style: TextStyle(color: Colors.grey.shade700),
),
),
),
),
),
const SizedBox(height: 16),
Center(
child: ElevatedButton.icon(
onPressed: _isLoading ? null : _showSignaturePad,
icon: const Icon(Icons.edit_note),
label: const Text("Update Signature"),
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
),
),
)
],
),
),
);
}
// --- END OF NEW WIDGET METHOD ---
Widget _buildProfileDetail(BuildContext context, String label, dynamic value) { Widget _buildProfileDetail(BuildContext context, String label, dynamic value) {
return Padding( return Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0), padding: const EdgeInsets.symmetric(vertical: 8.0),

View File

@ -150,6 +150,20 @@ class ApiService {
files: {'profile_picture': imageFile}); files: {'profile_picture': imageFile});
} }
// --- ADDED THIS NEW METHOD ---
/// Uploads the user's signature as a transparent PNG file.
Future<Map<String, dynamic>> uploadSignature(File imageFile) async {
final baseUrl = await _serverConfigService.getActiveApiUrl();
// We assume the endpoint is 'profile/upload-signature'
// and the server expects the file field name to be 'signature'.
return _baseService.postMultipart(
baseUrl: baseUrl,
endpoint: 'profile/upload-signature',
fields: {},
files: {'signature': imageFile});
}
// --- END OF NEW METHOD ---
Future<Map<String, dynamic>> refreshProfile() async { Future<Map<String, dynamic>> refreshProfile() async {
debugPrint('ApiService: Refreshing profile data from server...'); debugPrint('ApiService: Refreshing profile data from server...');
final result = await getProfile(); final result = await getProfile();

View File

@ -801,6 +801,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.4.1" version: "2.4.1"
signature:
dependency: "direct main"
description:
name: signature
sha256: "8056e091ad59c2eb5735fee975ec649d0caf8ce802bb1ffb1e0955b00a6d0daa"
url: "https://pub.dev"
source: hosted
version: "5.5.0"
simple_barcode_scanner: simple_barcode_scanner:
dependency: "direct main" dependency: "direct main"
description: description:

View File

@ -38,6 +38,7 @@ dependencies:
flutter_pdfview: ^1.3.2 flutter_pdfview: ^1.3.2
dio: ^5.4.3+1 dio: ^5.4.3+1
toggle_switch: ^2.3.0 toggle_switch: ^2.3.0
signature: ^5.4.1
# --- Device & Hardware Access --- # --- Device & Hardware Access ---
image_picker: ^1.0.7 image_picker: ^1.0.7