Velar/Frontend/lib/support/fetch_service.dart

42 lines
1.3 KiB
Dart
Raw Normal View History

2025-08-06 20:28:19 -07:00
// ignore_for_file: avoid_print
import 'package:http/http.dart' as http;
import 'dart:convert';
2025-08-14 21:54:25 -07:00
import 'package:shared_preferences/shared_preferences.dart';
2025-08-06 20:28:19 -07:00
import '../other_pages/enviroment.dart';
2025-08-14 21:54:25 -07:00
2025-08-06 20:28:19 -07:00
Future<List<Map<String, dynamic>>> fetchRecentTransactions() async {
2025-08-14 21:54:25 -07:00
try {
// 1⃣ Get userId from local storage
final prefs = await SharedPreferences.getInstance();
final userId = prefs.getString('userId');
if (userId == null || userId.isEmpty) {
print('❌ User ID not found — please log in again.');
return [];
}
// 2⃣ Create URI with userId
final uri = Uri.parse(
'${Environment.baseUrl}/api/transactions/recent',
).replace(queryParameters: {'userId': userId});
// 3⃣ Make API request
final response = await http.get(uri);
2025-08-06 20:28:19 -07:00
2025-08-14 21:54:25 -07:00
print('📡 Fetching recent transactions from: $uri');
print('Status code: ${response.statusCode}');
2025-08-06 20:28:19 -07:00
2025-08-14 21:54:25 -07:00
if (response.statusCode == 200) {
final List<dynamic> data = jsonDecode(response.body)['data'] ?? [];
return List<Map<String, dynamic>>.from(data);
} else {
print('❌ Failed to load recent transactions: ${response.body}');
return [];
}
} catch (e) {
print('⚠ Error fetching recent transactions: $e');
2025-08-06 20:28:19 -07:00
return [];
}
}