api_rest_flutter_mobile 3.0.0
api_rest_flutter_mobile: ^3.0.0 copied to clipboard
A comprehensive Flutter package for data management with online/offline capabilities, schema-driven validation, and bidirectional synchronization for iOS and Android applications.
example/example.dart
// ignore_for_file: avoid_print
/// Example demonstrating the basic usage of api_rest_flutter_mobile package.
///
/// This example shows the conceptual usage of the package.
/// For a complete working example, ensure all provider dependencies
/// are properly configured in your project.
library;
import 'dart:convert';
/// Basic usage example for api_rest_flutter_mobile
///
/// ## Setup
///
/// 1. Add the package to pubspec.yaml:
/// ```yaml
/// dependencies:
/// api_rest_flutter_mobile: ^1.0.0
/// ```
///
/// 2. Import required packages:
/// ```dart
/// import 'package:api_rest_flutter_mobile/api_rest.dart';
/// import 'package:flutter_data_cloud_provider/flutter_data_cloud_provider.dart';
/// import 'package:flutter_data_mobile_provider/flutter_data_mobile_provider.dart';
/// import 'package:flutter_models_provider/global/environment.dart';
/// ```
///
/// ## Initialize ApiRest
///
/// ```dart
/// void main() async {
/// WidgetsFlutterBinding.ensureInitialized();
///
/// final cloudDb = CloudDb(
/// endpointApi: 'https://your-api.com/api',
/// endpointAuth: 'https://your-api.com/auth',
/// );
///
/// final mobileDb = MobileDb();
///
/// final apiRest = ApiRest(
/// cloudDb: cloudDb,
/// mobileDb: mobileDb,
/// modeToWork: ModeToWork.online,
/// gestorData: GestorData.objectBox,
/// coleccionFuncionesBackend: 'funcionesBackend',
/// );
///
/// await apiRest.init();
/// runApp(MyApp());
/// }
/// ```
///
/// ## CRUD Operations Examples
///
/// ### Create a record
/// ```dart
/// final producto = ColeccionObjBox(
/// coleccion: 'productos',
/// estado: 'A',
/// data: jsonEncode({'nombre': 'Laptop', 'precio': 1299.99}),
/// );
///
/// final result = await apiRest.guardar<ColeccionObjBox>(
/// data: producto,
/// versionData: '1',
/// );
///
/// if (result.containsKey(EnvironmentApiRest.dataOk)) {
/// print('Created: ${result[EnvironmentApiRest.data]}');
/// }
/// ```
///
/// ### Read by ID
/// ```dart
/// final result = await apiRest.leeById<ColeccionObjBox>(
/// coleccion: 'productos',
/// consulta: '{"_id": "$productId"}',
/// argsLocalBD: [['idServer'], ['='], [productId]],
/// );
/// ```
///
/// ### Query records
/// ```dart
/// final result = await apiRest.obtener<ColeccionObjBox>(
/// coleccion: 'productos',
/// consulta: '{"data.activo": true}',
/// argsLocalBD: [['activo'], ['='], ['true']],
/// limit: '25',
/// );
/// ```
///
/// ### Update a record
/// ```dart
/// final result = await apiRest.actualizar<ColeccionObjBox>(
/// data: productoModificado,
/// versionData: '1',
/// );
/// ```
///
/// ### Synchronization
/// ```dart
/// // Upload local changes
/// await apiRest.uploadInfoToServer<ColeccionObjBox>(
/// coleccion: 'productos',
/// versionData: '1',
/// );
///
/// // Download from server
/// await apiRest.downLoadInfoFromServer<ColeccionObjBox>(
/// coleccion: 'productos',
/// );
/// ```
void main() {
// This is a documentation-only example.
// See the code comments above for usage examples.
print('api_rest_flutter_mobile example');
print('See documentation for complete usage examples.');
// Example of building a MongoDB query
final queryExample = buildMongoQuery(
activo: true,
categoria: 'electronica',
precioMin: 100,
precioMax: 2000,
);
print('MongoDB Query: $queryExample');
// Example of building ObjectBox args
final argsExample = buildObjectBoxArgs(
fields: ['activo', 'categoria'],
operators: ['=', '='],
values: ['true', 'electronica'],
);
print('ObjectBox Args: $argsExample');
}
/// Helper function to build MongoDB-style queries
String buildMongoQuery({
bool? activo,
String? categoria,
double? precioMin,
double? precioMax,
}) {
final conditions = <Map<String, dynamic>>[];
if (activo != null) {
conditions.add({'data.activo': activo});
}
if (categoria != null) {
conditions.add({'data.categoria': categoria});
}
if (precioMin != null || precioMax != null) {
final priceCondition = <String, dynamic>{};
if (precioMin != null) priceCondition['\$gte'] = precioMin;
if (precioMax != null) priceCondition['\$lte'] = precioMax;
conditions.add({'data.precio': priceCondition});
}
if (conditions.isEmpty) {
return '{}';
}
if (conditions.length == 1) {
return jsonEncode(conditions.first);
}
return jsonEncode({'\$and': conditions});
}
/// Helper function to build ObjectBox query arguments
List<List<String>> buildObjectBoxArgs({
required List<String> fields,
required List<String> operators,
required List<String> values,
}) {
assert(fields.length == operators.length && operators.length == values.length,
'All lists must have the same length');
return [fields, operators, values];
}
/// Example response handler
void handleApiResponse(Map<String, dynamic> response) {
// Check for success using the constant keys
// In real code: EnvironmentApiRest.dataOk and EnvironmentApiRest.dataNOk
if (response.containsKey('dataOk')) {
final data = response['data'];
print('Success: $data');
} else if (response.containsKey('dataNOk')) {
final error = response['error'];
print('Error: $error');
}
}