usuarios_view_model.dart 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import 'dart:convert';
  2. import 'package:flutter/material.dart';
  3. import 'package:sqflite/sqflite.dart';
  4. import '../../core/services/services.dart';
  5. import '../../core/models/models.dart';
  6. class UsuarioViewModel extends ChangeNotifier {
  7. List<Usuario> _usuarios = [];
  8. bool _isLoading = false;
  9. List<Usuario> get usuarios => _usuarios;
  10. bool get isLoading => _isLoading;
  11. int _currentPage = 1;
  12. int _totalProducts = 0;
  13. int _limit = 10;
  14. int get currentPage => _currentPage;
  15. int get totalProducts => _totalProducts;
  16. int get totalPages => (_totalProducts / _limit).ceil();
  17. Future<void> fetchLocalAll({int page = 1}) async {
  18. _currentPage = page;
  19. var db = await DatabaseService().db;
  20. int? count = Sqflite.firstIntValue(
  21. await db!.rawQuery('SELECT COUNT(*) FROM Usuario'));
  22. _totalProducts = count ?? 0;
  23. int offset = (_limit * (page - 1));
  24. var query = await db.query('Usuario',
  25. where: 'eliminado IS NULL',
  26. orderBy: 'id asc',
  27. limit: _limit,
  28. offset: offset);
  29. _usuarios = query.map((element) => Usuario.fromJson(element)).toList();
  30. notifyListeners();
  31. }
  32. Future<bool> sincronizarUsuarios() async {
  33. try {
  34. Map<String, String> parametros = {"expand": 'permisos'};
  35. final response = ApiResponse(
  36. await BaseService().get('/pos/usuario', queryParameters: parametros));
  37. if (response.isOk && response.resultados != null) {
  38. List<Usuario> usuariosApi =
  39. response.resultados!.map((json) => Usuario.fromApi(json)).toList();
  40. if (usuariosApi.isNotEmpty) {
  41. await DatabaseService().sincronizarUsuarios(usuariosApi);
  42. notifyListeners();
  43. return true;
  44. }
  45. }
  46. return false;
  47. } catch (e) {
  48. print('Error al sincronizar usuarios: $e');
  49. return false;
  50. }
  51. }
  52. }