Skip to content

Overview

  • File: lib/main.dart

The main.dart file serves as the entry point for the HVC XR application, handling initialization, configuration, and setup of core components. This document provides a detailed explanation of the file's structure and functionality.

Global Variables

dart
bool isProd = true;
late String deviceId;
late String deviceType;
late String deviceAgent;
late bool isDeviceHmt, isNavigator500, isCimo, isDigiLens;
late PackageInfo appInfo;
RxBool isInCall = false.obs;
DbManager? dbManager;
HippoDBManager? hippoDBManager;
Logger log = Logger('HVC_XR_LOGGER');

Variable Descriptions

  • isProd: Production environment flag
  • deviceId: Unique identifier for the device
  • deviceType: Type of device (e.g., HMT-1, Navigator 500)
  • deviceAgent: User agent string for API requests
  • isDeviceHmt, isNavigator500, isCimo, isDigiLens: Device type flags
  • appInfo: Package information for the application
  • isInCall: Reactive boolean for call state
  • dbManager: Database manager instance
  • hippoDBManager: Hippo database manager instance
  • log: Logger instance for application logging

Main Function

The main() function handles the application's initialization process:

dart
void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  try {
    // Initialization steps...
  } catch (e) {
    logInfo(e);
  }
}

Initialization Steps

  1. Logging Setup

    dart
    Logger.root.activateLogcat();
    Logger.root.level = Level.ALL;
  2. Storage Initialization

    dart
    await GetStorage.init();
  3. Device Detection

    dart
    isDeviceHmt = await isHmt;
    isNavigator500 = await isNav500;
    isCimo = await isCimoOrXps;
    isDigiLens = await isDigiLensDevice;
  4. Permission Requests

    dart
    Map<Permission, PermissionStatus> statuses = await [
      Permission.camera,
      Permission.microphone,
      Permission.storage,
      Permission.mediaLibrary,
      Permission.manageExternalStorage,
      Permission.notification,
    ].request();
  5. Database Initialization

    dart
    dbManager = dbManager ?? await DbManager.create();
    hippoDBManager = hippoDBManager ?? await HippoDBManager.initiate();
  6. Background Service Setup

    dart
    Workmanager().initialize(
      workToDoInBackgroundService,
      isInDebugMode: false,
    );
    Workmanager().registerPeriodicTask(
      "hvc_xr",
      "fileUpload",
      backoffPolicy: BackoffPolicy.linear,
    );
  7. Device Information Setup

    dart
    deviceId = isDigiLens ? 'DigiLens' : await getDeviceId();
    appInfo = await PackageInfo.fromPlatform();
    deviceType = await getDeviceType();
    deviceAgent = 'HvcHeadset->$deviceType->$deviceId';
  8. Orientation Configuration

    dart
    await SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);
  9. Push Notification Setup

    dart
    OneSignal.Debug.setLogLevel(OSLogLevel.verbose);
    OneSignal.initialize('5bc6d3bd-8862-48c9-b172-435f8b3c75b4');
    OneSignal.Notifications.requestPermission(true);

MyApp Widget

The MyApp widget is the root widget of the application:

dart
class MyApp extends StatefulWidget {
  MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

Controller Initialization

The following controllers are initialized in _MyAppState:

dart
final digilensController = Get.put(DigilensController());
final authController = Get.put(AuthController());
final contactsController = Get.put(ContactsController());
final schedulesController = Get.put(EventsController());
final meetingsController = Get.put(MeetingsController());
final realTimeController = Get.put(RealTimeController());
final messagesController = Get.put(MessagesController());
final mediaController = Get.put(MediaController());

Application Lifecycle Management

The application handles lifecycle events in _MyAppState:

dart
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
  super.didChangeAppLifecycleState(state);
  switch (state) {
    case AppLifecycleState.inactive:
      print('appLifeCycleState inactive');
      break;
    case AppLifecycleState.resumed:
      if (isLoggedIn()) {
        realTimeController.onInit().whenComplete(() async =>
            await realTimeController.callHi('AppLifecycleState.resumed'));
      }
      print('appLifeCycleState resumed');
      break;
    case AppLifecycleState.paused:
      authController.saveClosingTime();
      print('appLifeCycleState paused');
      break;
    case AppLifecycleState.detached:
      break;
  }
}

Error Handling

The application implements error handling at multiple levels:

  1. Main Function Error Handling

    dart
    try {
      // Initialization code
    } catch (e) {
      logInfo(e);
    }
  2. Laser Permission Error Handling

    dart
    Future<void> requestLaserPermission() async {
      try {
        await laserChannel.invokeMethod('requestLaserPermission');
      } catch (e) {
        logInfo(e);
      }
    }

Best Practices

  1. Always check device type before implementing device-specific features
  2. Handle permissions appropriately for each device type
  3. Implement proper error handling for all async operations
  4. Clean up resources in the dispose method
  5. Use reactive state management with GetX
  6. Follow the established controller initialization pattern

Common Issues and Solutions

  1. Permission Denials

    • Ensure all required permissions are requested
    • Handle permission denials gracefully
    • Provide clear user feedback
  2. Device Detection Issues

    • Verify device detection methods
    • Implement fallback options
    • Log device detection results
  3. Background Service Problems

    • Check Workmanager initialization
    • Verify task registration
    • Monitor task execution

Testing

  1. Test initialization on different devices
  2. Verify permission handling
  3. Check background service functionality
  4. Test application lifecycle management
  5. Verify controller initialization

Dependencies

The main file relies on several key dependencies:

  • get: State management
  • get_storage: Local storage
  • logging_to_logcat: Logging
  • onesignal_flutter: Push notifications
  • permission_handler: Permission management
  • workmanager: Background tasks
  • flutter_screenutil: Screen utilities

This documentation provides a comprehensive guide for understanding and working with the main.dart file. For specific implementation details, refer to the inline documentation in the source code.

Released under the MIT License.