Files
GSFV2/gsf/lib/main.dart
2024-04-22 23:50:28 -07:00

310 lines
10 KiB
Dart

import 'dart:async';
import 'dart:io';
// import 'package:firebase_dynamic_links/firebase_dynamic_links.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:gsp_app/scale/utils/local_storage.dart';
import 'package:gsp_app/view_model/StepcountController.dart';
import 'package:gsp_app/view_model/Stepcounts.dart';
import 'package:gsp_app/view_model/app_data_controller.dart';
import 'package:gsp_app/views/pages/splash.dart';
import 'package:gsp_app/views/theme.dart';
import 'package:icdevicemanager_flutter/ic_bluetooth_sdk.dart';
import 'package:icdevicemanager_flutter/model/other/ICDeviceManagerConfig.dart';
import 'package:injectable/injectable.dart';
import 'package:onesignal_flutter/onesignal_flutter.dart';
import 'package:pedometer/pedometer.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'repository/services/rateUs/ratingController.dart';
import 'views/pages/intro/get_started.dart';
import 'views/short_video_player/svp_lib/injection.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
configureInjection(Environment.prod);
await SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
await Firebase.initializeApp();
const fatalError = true;
// Non-async exceptions
FlutterError.onError = (errorDetails) {
if (fatalError) {
// If you want to record a "fatal" exception
FirebaseCrashlytics.instance.recordFlutterFatalError(errorDetails);
// ignore: dead_code
} else {
// If you want to record a "non-fatal" exception
FirebaseCrashlytics.instance.recordFlutterError(errorDetails);
}
};
// Async exceptions
PlatformDispatcher.instance.onError = (error, stack) {
if (fatalError) {
// If you want to record a "fatal" exception
FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
// ignore: dead_code
} else {
// If you want to record a "non-fatal" exception
FirebaseCrashlytics.instance.recordError(error, stack);
}
return true;
};
await GetStorage.init();
OneSignal.shared.setLogLevel(OSLogLevel.verbose, OSLogLevel.none);
OneSignal.shared.setAppId(
"41397809-455f-4d3a-bfa7-f190a4d078e4"); //f5869a6b-cf12-422d-91e3-286f9c0e1a62
OneSignal.shared.setExternalUserId("8879");
OneSignal.shared.promptUserForPushNotificationPermission().then(
(accepted) => print("Accepted Permission $accepted"),
);
final status = await OneSignal.shared.getDeviceState();
final String? playerId = status!.userId;
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString("playerId", playerId.toString());
print("playerId $playerId");
Get.put(AppDataController()); //init controller
if (Platform.isAndroid) {
WidgetsFlutterBinding.ensureInitialized();
[
Permission.location,
Permission.storage,
Permission.bluetooth,
Permission.bluetoothConnect,
Permission.bluetoothScan,
Permission.activityRecognition,
].request().then((value) {
runApp(const MyApp());
});
} else {
runApp(const MyApp());
}
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
final RatingController ratingController = Get.put(RatingController());
class _MyAppState extends State<MyApp> {
//pedometer module variables
late Stream<StepCount> _stepCountStream;
String _steps = '?';
// Initialize a step count variable and a date variable
int? _appStepCount;
DateTime _currentDate = DateTime.now();
StepCountController stepController = Get.put(StepCountController());
@override
void initState() {
super.initState();
// initShortClipLinks();
ratingController.loadRatingFromPrefs();
LocalStorage.init();
IcBluetoothSdk.instance.initSDK(ICDeviceManagerConfig());
checkLocationStatus();
// initPlatformState();
//For step count Module
if (Platform.isAndroid) {
permissionDialog();
getStepCountFromStorage();
// checkAndUpdateDate();
storeSteps();
}
}
storeSteps() {
Timer.periodic(const Duration(minutes: 1), (timer) {
Map<String, dynamic> updata = {"step_count": _appStepCount};
StepCounts().storeSteps(updata);
});
}
permissionDialog() async {
// Map<Permission, PermissionStatus> statuses = await [
// Permission.activityRecognition,
// ].request();
if (await Permission.activityRecognition.isGranted) {
initPlatformState();
}
}
int _storedStepCount = 0;
void initPlatformState() {
_stepCountStream = Pedometer.stepCountStream;
_stepCountStream.listen(onStepCount).onError(onStepCountError);
if (!mounted) return;
}
int finalSteps = 0;
void onStepCount(StepCount event) async {
if (_appStepCount == null) {
// Set the initial step count when the stream first emits a value
_storedStepCount = event.steps;
await storeFirstEmittedValueOfDay(_storedStepCount);
int stepsSinceLastStoredCount = event.steps - _storedStepCount;
stepController.appStepCountGlobal.value = stepsSinceLastStoredCount;
updateAndPersistStepCount(stepsSinceLastStoredCount);
_appStepCount = stepsSinceLastStoredCount;
} else {
_storedStepCount = await getFirstEmittedValueOfDay();
finalSteps = event.steps - _storedStepCount;
_appStepCount = finalSteps;
stepController.appStepCountGlobal.value = finalSteps;
}
// // Check if the step count is a multiple of 1000
// if (_appStepCount! % 1000 == 0) {
// // Call the API to store steps
// Map<String, dynamic> updata = {"step_count": _appStepCount};
// StepCounts().storeSteps(updata);
// }
}
storeFirstEmittedValueOfDay(_storedStepCount) async {
final prefs = await SharedPreferences.getInstance();
final currentDateKey = "emitted" +
_currentDate
.toLocal()
.toString()
.split(' ')[0]; // Use the date as the key
prefs.setInt(currentDateKey, _storedStepCount);
}
getFirstEmittedValueOfDay() async {
final currentDateKey =
"emitted" + _currentDate.toLocal().toString().split(' ')[0];
final prefs = await SharedPreferences.getInstance();
final emittedValueCount = prefs.getInt(currentDateKey);
return emittedValueCount!;
}
// Function to reset the daily step count
void resetDailyStepCount() {
_storedStepCount = 0;
}
//-----+++++++++++----- old logic
// void initPlatformState() {
// _stepCountStream = Pedometer.stepCountStream;
// _stepCountStream.listen(onStepCount).onError(onStepCountError);
// if (!mounted) return;
// }
// // When you receive step count updates from the pedometer package:
// void onStepCount(StepCount event) {
// _steps = event.steps.toString();
// _appStepCount = _appStepCount + 1;
// stepController.appStepCountGlobal.value = _appStepCount;
// updateAndPersistStepCount(null);
// // Check if the step count is a multiple of 1000
// if (_appStepCount % 1000 == 0) {
// // Call the API to store steps
// Map<String, dynamic> updata = {"step_count": _appStepCount};
// StepCounts().storeSteps(updata);
// }
// }
//-----+++++++++++----- old logic end
void onStepCountError(error) {
print('onStepCountError: $error');
setState(() {
_steps = 'Step Count not available';
});
}
// //Function to check and update the current date
// void checkAndUpdateDate() {
// final today = DateTime.now();
// if (today.day != _currentDate.day) {
// // The date has changed, reset the step count and update the current date
// updateAndPersistStepCount(0);
// _currentDate = today;
// }
// }
// Function to retrieve the step count from storage during app initialization
void getStepCountFromStorage() async {
final currentDateKey = _currentDate.toLocal().toString().split(' ')[0];
final prefs = await SharedPreferences.getInstance();
final storedCount = prefs.getInt(currentDateKey);
setState(() {
_appStepCount = storedCount;
stepController.appStepCountGlobal.value = _appStepCount ?? 0;
});
}
// Function to update and persist the step count
void updateAndPersistStepCount(int? manualCount) async {
final prefs = await SharedPreferences.getInstance();
final currentDateKey = _currentDate
.toLocal()
.toString()
.split(' ')[0]; // Use the date as the key
prefs.setInt(currentDateKey, manualCount!);
}
checkLocationStatus() async {
Map<Permission, PermissionStatus> statuses = await [
Permission.location,
Permission.storage,
Permission.bluetooth,
].request();
}
@override
Widget build(BuildContext context) {
// initUniLinks();
//initOnesignal();
final isloggedins = GetStorage().read("isLoggedIn") ?? false;
print('isloggedins $isloggedins');
// var moodResult = await MoodOMeterService().getMoodOMeter();
// // if()
// if(moodResult.responseStatus != ResponseStatus.success ){
// return const HomePageSkeleton();
// }
return GetMaterialApp(
// theme,
builder: (context, child) {
return MediaQuery(
data: MediaQuery.of(context).copyWith(textScaleFactor: 1),
child: child!,
);
},
theme: AppTheme.light(),
darkTheme: AppTheme.dark(),
themeMode: ThemseServices().theme,
// theme: ThemeData(
// fontFamily: 'Poppins',
// textTheme: Theme.of(context).textTheme.apply(
// bodyColor: Colors.white,
// displayColor: Colors.white,
// ),
// ),
debugShowCheckedModeBanner: false,
home:
//PeriodCalendar(), //
isloggedins ? const SplashScreen() : const Getstarted(),
// home: AgeInputForm(),
// home: StoryViewr(),
);
}
}