first commit

This commit is contained in:
kicap
2025-07-13 06:59:30 +08:00
commit 86d84de7e3
165 changed files with 7941 additions and 0 deletions

52
lib/app/app.dart Normal file
View File

@ -0,0 +1,52 @@
import 'package:stacked_services/stacked_services.dart';
import 'package:stacked/stacked_annotations.dart';
import '../services/http_services.dart';
import '../services/my_easyloading.dart';
import '../services/my_notification.dart';
import '../services/my_preferences.dart';
import '../services/my_socket_io_client.dart';
import '../services/other_function.dart';
import '../ui/views/login/login_view.dart';
import '../ui/views/nav_bar/log_data/log_data_view.dart';
import '../ui/views/nav_bar/monitoring/monitoring_view.dart';
import '../ui/views/nav_bar/nav_bar_view.dart';
import '../ui/views/splash_screen/splash_screen_view.dart';
@StackedApp(
routes: [
MaterialRoute(page: SplashScreenView, initial: true),
MaterialRoute(page: LoginView),
MaterialRoute(
page: NavBarView,
children: [
MaterialRoute(page: MonitoringView),
MaterialRoute(page: LogDataView),
],
),
],
// dialogs: [
// StackedDialog(classType: ScanRfidDialogView),
// ],
// bottomsheets: [
// StackedBottomsheet(classType: DetailLogHistoryView),
// ],
dependencies: [
LazySingleton(classType: NavigationService),
LazySingleton(classType: DialogService),
LazySingleton(classType: SnackbarService),
LazySingleton(classType: BottomSheetService),
//
LazySingleton(classType: MyEasyLoading),
LazySingleton(classType: MyHttpServices),
LazySingleton(classType: OtherFunction),
LazySingleton(classType: MySocketIoClient),
LazySingleton(classType: MyNotification),
LazySingleton(classType: MySharedPrefs)
],
logger: StackedLogger(),
)
class App {}

43
lib/app/app.locator.dart Normal file
View File

@ -0,0 +1,43 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
// **************************************************************************
// StackedLocatorGenerator
// **************************************************************************
// ignore_for_file: public_member_api_docs, implementation_imports, depend_on_referenced_packages
import 'package:stacked_services/src/bottom_sheet/bottom_sheet_service.dart';
import 'package:stacked_services/src/dialog/dialog_service.dart';
import 'package:stacked_services/src/navigation/navigation_service.dart';
import 'package:stacked_services/src/snackbar/snackbar_service.dart';
import 'package:stacked_shared/stacked_shared.dart';
import '../services/http_services.dart';
import '../services/my_easyloading.dart';
import '../services/my_notification.dart';
import '../services/my_preferences.dart';
import '../services/my_socket_io_client.dart';
import '../services/other_function.dart';
final locator = StackedLocator.instance;
Future<void> setupLocator({
String? environment,
EnvironmentFilter? environmentFilter,
}) async {
// Register environments
locator.registerEnvironment(
environment: environment, environmentFilter: environmentFilter);
// Register dependencies
locator.registerLazySingleton(() => NavigationService());
locator.registerLazySingleton(() => DialogService());
locator.registerLazySingleton(() => SnackbarService());
locator.registerLazySingleton(() => BottomSheetService());
locator.registerLazySingleton(() => MyEasyLoading());
locator.registerLazySingleton(() => MyHttpServices());
locator.registerLazySingleton(() => OtherFunction());
locator.registerLazySingleton(() => MySocketIoClient());
locator.registerLazySingleton(() => MyNotification());
locator.registerLazySingleton(() => MySharedPrefs());
}

159
lib/app/app.logger.dart Normal file
View File

@ -0,0 +1,159 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
// **************************************************************************
// StackedLoggerGenerator
// **************************************************************************
// ignore_for_file: avoid_print, depend_on_referenced_packages
/// Maybe this should be generated for the user as well?
///
/// import 'package:customer_app/services/stackdriver/stackdriver_service.dart';
import 'package:flutter/foundation.dart';
import 'package:logger/logger.dart';
class SimpleLogPrinter extends LogPrinter {
final String className;
final bool printCallingFunctionName;
final bool printCallStack;
final List<String> exludeLogsFromClasses;
final String? showOnlyClass;
SimpleLogPrinter(
this.className, {
this.printCallingFunctionName = true,
this.printCallStack = false,
this.exludeLogsFromClasses = const [],
this.showOnlyClass,
});
@override
List<String> log(LogEvent event) {
var color = PrettyPrinter.levelColors[event.level];
var emoji = PrettyPrinter.levelEmojis[event.level];
var methodName = _getMethodName();
var methodNameSection =
printCallingFunctionName && methodName != null ? ' | $methodName' : '';
var stackLog = event.stackTrace.toString();
var output =
'$emoji $className$methodNameSection - ${event.message}${event.error != null ? '\nERROR: ${event.error}\n' : ''}${printCallStack ? '\nSTACKTRACE:\n$stackLog' : ''}';
if (exludeLogsFromClasses
.any((excludeClass) => className == excludeClass) ||
(showOnlyClass != null && className != showOnlyClass)) return [];
final pattern = RegExp('.{1,800}'); // 800 is the size of each chunk
List<String> result = [];
for (var line in output.split('\n')) {
result.addAll(pattern.allMatches(line).map((match) {
if (kReleaseMode) {
return match.group(0)!;
} else {
return color!(match.group(0)!);
}
}));
}
return result;
}
String? _getMethodName() {
try {
final currentStack = StackTrace.current;
final formattedStacktrace = _formatStackTrace(currentStack, 3);
if (kIsWeb) {
final classNameParts = _splitClassNameWords(className);
return _findMostMatchedTrace(formattedStacktrace!, classNameParts)
.split(' ')
.last;
} else {
final realFirstLine = formattedStacktrace
?.firstWhere((line) => line.contains(className), orElse: () => "");
final methodName = realFirstLine?.replaceAll('$className.', '');
return methodName;
}
} catch (e) {
// There's no deliberate function call from our code so we return null;
return null;
}
}
List<String> _splitClassNameWords(String className) {
return className
.split(RegExp(r'(?=[A-Z])'))
.map((e) => e.toLowerCase())
.toList();
}
/// When the faulty word exists in the begging this method will not be very usefull
String _findMostMatchedTrace(
List<String> stackTraces, List<String> keyWords) {
String match = stackTraces.firstWhere(
(trace) => _doesTraceContainsAllKeywords(trace, keyWords),
orElse: () => '');
if (match.isEmpty) {
match = _findMostMatchedTrace(
stackTraces, keyWords.sublist(0, keyWords.length - 1));
}
return match;
}
bool _doesTraceContainsAllKeywords(String stackTrace, List<String> keywords) {
final formattedKeywordsAsRegex = RegExp(keywords.join('.*'));
return stackTrace.contains(formattedKeywordsAsRegex);
}
}
final stackTraceRegex = RegExp(r'#[0-9]+[\s]+(.+) \(([^\s]+)\)');
List<String>? _formatStackTrace(StackTrace stackTrace, int methodCount) {
var lines = stackTrace.toString().split('\n');
var formatted = <String>[];
var count = 0;
for (var line in lines) {
var match = stackTraceRegex.matchAsPrefix(line);
if (match != null) {
if (match.group(2)!.startsWith('package:logger')) {
continue;
}
var newLine = ("${match.group(1)}");
formatted.add(newLine.replaceAll('<anonymous closure>', '()'));
if (++count == methodCount) {
break;
}
} else {
formatted.add(line);
}
}
if (formatted.isEmpty) {
return null;
} else {
return formatted;
}
}
Logger getLogger(
String className, {
bool printCallingFunctionName = true,
bool printCallstack = false,
List<String> exludeLogsFromClasses = const [],
String? showOnlyClass,
}) {
return Logger(
printer: SimpleLogPrinter(
className,
printCallingFunctionName: printCallingFunctionName,
printCallStack: printCallstack,
showOnlyClass: showOnlyClass,
exludeLogsFromClasses: exludeLogsFromClasses,
),
output: MultiOutput([
if (!kReleaseMode) ConsoleOutput(),
]),
);
}

262
lib/app/app.router.dart Normal file
View File

@ -0,0 +1,262 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
// **************************************************************************
// StackedNavigatorGenerator
// **************************************************************************
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'package:flutter/material.dart' as _i5;
import 'package:flutter/material.dart';
import 'package:ont_app2/ui/views/login/login_view.dart' as _i3;
import 'package:ont_app2/ui/views/nav_bar/log_data/log_data_view.dart' as _i7;
import 'package:ont_app2/ui/views/nav_bar/monitoring/monitoring_view.dart'
as _i6;
import 'package:ont_app2/ui/views/nav_bar/nav_bar_view.dart' as _i4;
import 'package:ont_app2/ui/views/splash_screen/splash_screen_view.dart' as _i2;
import 'package:stacked/stacked.dart' as _i1;
import 'package:stacked_services/stacked_services.dart' as _i8;
class Routes {
static const splashScreenView = '/';
static const loginView = '/login-view';
static const navBarView = '/nav-bar-view';
static const all = <String>{
splashScreenView,
loginView,
navBarView,
};
}
class StackedRouter extends _i1.RouterBase {
final _routes = <_i1.RouteDef>[
_i1.RouteDef(
Routes.splashScreenView,
page: _i2.SplashScreenView,
),
_i1.RouteDef(
Routes.loginView,
page: _i3.LoginView,
),
_i1.RouteDef(
Routes.navBarView,
page: _i4.NavBarView,
),
];
final _pagesMap = <Type, _i1.StackedRouteFactory>{
_i2.SplashScreenView: (data) {
return _i5.MaterialPageRoute<dynamic>(
builder: (context) => const _i2.SplashScreenView(),
settings: data,
);
},
_i3.LoginView: (data) {
return _i5.MaterialPageRoute<dynamic>(
builder: (context) => _i3.LoginView(),
settings: data,
);
},
_i4.NavBarView: (data) {
return _i5.MaterialPageRoute<dynamic>(
builder: (context) => const _i4.NavBarView(),
settings: data,
);
},
};
@override
List<_i1.RouteDef> get routes => _routes;
@override
Map<Type, _i1.StackedRouteFactory> get pagesMap => _pagesMap;
}
class NavBarViewRoutes {
static const monitoringView = 'monitoring-view';
static const logDataView = 'log-data-view';
static const all = <String>{
monitoringView,
logDataView,
};
}
class NavBarViewRouter extends _i1.RouterBase {
final _routes = <_i1.RouteDef>[
_i1.RouteDef(
NavBarViewRoutes.monitoringView,
page: _i6.MonitoringView,
),
_i1.RouteDef(
NavBarViewRoutes.logDataView,
page: _i7.LogDataView,
),
];
final _pagesMap = <Type, _i1.StackedRouteFactory>{
_i6.MonitoringView: (data) {
return _i5.MaterialPageRoute<dynamic>(
builder: (context) => const _i6.MonitoringView(),
settings: data,
);
},
_i7.LogDataView: (data) {
return _i5.MaterialPageRoute<dynamic>(
builder: (context) => const _i7.LogDataView(),
settings: data,
);
},
};
@override
List<_i1.RouteDef> get routes => _routes;
@override
Map<Type, _i1.StackedRouteFactory> get pagesMap => _pagesMap;
}
extension NavigatorStateExtension on _i8.NavigationService {
Future<dynamic> navigateToSplashScreenView([
int? routerId,
bool preventDuplicates = true,
Map<String, String>? parameters,
Widget Function(BuildContext, Animation<double>, Animation<double>, Widget)?
transition,
]) async {
return navigateTo<dynamic>(Routes.splashScreenView,
id: routerId,
preventDuplicates: preventDuplicates,
parameters: parameters,
transition: transition);
}
Future<dynamic> navigateToLoginView([
int? routerId,
bool preventDuplicates = true,
Map<String, String>? parameters,
Widget Function(BuildContext, Animation<double>, Animation<double>, Widget)?
transition,
]) async {
return navigateTo<dynamic>(Routes.loginView,
id: routerId,
preventDuplicates: preventDuplicates,
parameters: parameters,
transition: transition);
}
Future<dynamic> navigateToNavBarView([
int? routerId,
bool preventDuplicates = true,
Map<String, String>? parameters,
Widget Function(BuildContext, Animation<double>, Animation<double>, Widget)?
transition,
]) async {
return navigateTo<dynamic>(Routes.navBarView,
id: routerId,
preventDuplicates: preventDuplicates,
parameters: parameters,
transition: transition);
}
Future<dynamic> navigateToNestedMonitoringViewInNavBarViewRouter([
int? routerId,
bool preventDuplicates = true,
Map<String, String>? parameters,
Widget Function(BuildContext, Animation<double>, Animation<double>, Widget)?
transition,
]) async {
return navigateTo<dynamic>(NavBarViewRoutes.monitoringView,
id: routerId,
preventDuplicates: preventDuplicates,
parameters: parameters,
transition: transition);
}
Future<dynamic> navigateToNestedLogDataViewInNavBarViewRouter([
int? routerId,
bool preventDuplicates = true,
Map<String, String>? parameters,
Widget Function(BuildContext, Animation<double>, Animation<double>, Widget)?
transition,
]) async {
return navigateTo<dynamic>(NavBarViewRoutes.logDataView,
id: routerId,
preventDuplicates: preventDuplicates,
parameters: parameters,
transition: transition);
}
Future<dynamic> replaceWithSplashScreenView([
int? routerId,
bool preventDuplicates = true,
Map<String, String>? parameters,
Widget Function(BuildContext, Animation<double>, Animation<double>, Widget)?
transition,
]) async {
return replaceWith<dynamic>(Routes.splashScreenView,
id: routerId,
preventDuplicates: preventDuplicates,
parameters: parameters,
transition: transition);
}
Future<dynamic> replaceWithLoginView([
int? routerId,
bool preventDuplicates = true,
Map<String, String>? parameters,
Widget Function(BuildContext, Animation<double>, Animation<double>, Widget)?
transition,
]) async {
return replaceWith<dynamic>(Routes.loginView,
id: routerId,
preventDuplicates: preventDuplicates,
parameters: parameters,
transition: transition);
}
Future<dynamic> replaceWithNavBarView([
int? routerId,
bool preventDuplicates = true,
Map<String, String>? parameters,
Widget Function(BuildContext, Animation<double>, Animation<double>, Widget)?
transition,
]) async {
return replaceWith<dynamic>(Routes.navBarView,
id: routerId,
preventDuplicates: preventDuplicates,
parameters: parameters,
transition: transition);
}
Future<dynamic> replaceWithNestedMonitoringViewInNavBarViewRouter([
int? routerId,
bool preventDuplicates = true,
Map<String, String>? parameters,
Widget Function(BuildContext, Animation<double>, Animation<double>, Widget)?
transition,
]) async {
return replaceWith<dynamic>(NavBarViewRoutes.monitoringView,
id: routerId,
preventDuplicates: preventDuplicates,
parameters: parameters,
transition: transition);
}
Future<dynamic> replaceWithNestedLogDataViewInNavBarViewRouter([
int? routerId,
bool preventDuplicates = true,
Map<String, String>? parameters,
Widget Function(BuildContext, Animation<double>, Animation<double>, Widget)?
transition,
]) async {
return replaceWith<dynamic>(NavBarViewRoutes.logDataView,
id: routerId,
preventDuplicates: preventDuplicates,
parameters: parameters,
transition: transition);
}
}

View File

@ -0,0 +1,27 @@
import 'package:stacked/stacked.dart';
import 'package:stacked_services/stacked_services.dart';
import '../../services/http_services.dart';
import '../../services/my_easyloading.dart';
import '../../services/my_notification.dart';
import '../../services/my_preferences.dart';
import '../../services/my_socket_io_client.dart';
import '../../services/other_function.dart';
import '../app.locator.dart';
class CustomBaseViewModel extends BaseViewModel {
final dialogService = locator<DialogService>();
final navigationService = locator<NavigationService>();
final bottomSheetService = locator<BottomSheetService>();
final snackbarService = locator<SnackbarService>();
final otherFunction = locator<OtherFunction>();
final socketIoClient = locator<MySocketIoClient>();
final httpService = locator<MyHttpServices>();
final easyLoading = locator<MyEasyLoading>();
final myNotification = locator<MyNotification>();
final mySharedPrefs = locator<MySharedPrefs>();
void back() {
navigationService.back();
}
}

View File

@ -0,0 +1 @@
enum SnackbarType { sukses, gagal, info }

View File

@ -0,0 +1,53 @@
import 'package:flutter/material.dart';
import 'package:stacked_services/stacked_services.dart';
import 'app.locator.dart';
import 'enum/snackbar_enum.dart';
void setupSnackbarUi() {
final service = locator<SnackbarService>();
service.registerCustomSnackbarConfig(
variant: SnackbarType.sukses,
config: SnackbarConfig(
backgroundColor: Colors.black.withOpacity(.5),
textColor: Colors.green,
borderRadius: 50,
icon: Icon(
Icons.check,
color: Colors.green,
),
snackPosition: SnackPosition.TOP,
margin: EdgeInsets.all(10),
),
);
service.registerCustomSnackbarConfig(
variant: SnackbarType.gagal,
config: SnackbarConfig(
backgroundColor: Colors.black.withOpacity(.5),
textColor: Colors.red,
borderRadius: 50,
icon: Icon(
Icons.close,
color: Colors.red,
),
snackPosition: SnackPosition.TOP,
margin: EdgeInsets.all(10),
),
);
service.registerCustomSnackbarConfig(
variant: SnackbarType.info,
config: SnackbarConfig(
backgroundColor: Colors.black.withOpacity(.5),
textColor: Colors.blue,
borderRadius: 50,
icon: Icon(
Icons.info,
color: Colors.blue,
),
snackPosition: SnackPosition.TOP,
margin: EdgeInsets.all(10),
),
);
}

30
lib/app/themes/app_colors.dart Executable file
View File

@ -0,0 +1,30 @@
import 'dart:ui';
const Color mainColor = Color.fromARGB(255, 238, 6, 6);
const Color secondaryColor = Color(0xFFB72025);
const Color dangerColor = Color(0xFFFF4B68);
const Color warningColor = Color(0xFFFBFFA3);
const Color lightColor = Color(0xFFF4FAFE);
const Color lightGreyColor = Color(0xFFFCFCFC);
const Color stockColor = Color(0xFFEEF3F6);
const Color backgroundColor = Color(0xFFE5E5E5);
const Color backgroundColor3 = Color(0xFFF6F7F8);
const Color orangeColor = Color.fromARGB(255, 250, 145, 84);
const Color blueColor = Color(0xFF026AA2);
const Color greenColor = Color(0xFF2ABB52);
const Color redColor = Color(0xFFED1717);
const Color greyBlueColor = Color(0xFF363F72);
const Color fontColor = Color(0xFF101828);
const Color fontSecondaryColor = Color(0xFF667085);
const Color fontParagraphColor = Color(0xFFB2B2B2);
const Color fontGrey = Color(0xFF1C1C1C);
const Color mainGrey = Color(0xFF8991A4);
const Color secondaryGrey = Color(0xFFD0D5DD);
const Color thirdGrey = Color(0xFFF2F4F7);
const Color fourthGrey = Color(0xFF5C5C5C);
const Color fifthGrey = Color(0xFFEBEBEB);
const Color sixthGrey = Color(0xFF151515);

View File

@ -0,0 +1,44 @@
import 'package:flutter/material.dart';
import 'app_colors.dart';
const regularTextStyle = TextStyle(
fontFamily: 'Arial',
fontSize: 14,
fontWeight: FontWeight.w400,
color: fontColor);
const italicTextStyle = TextStyle(
fontFamily: 'Arial',
fontSize: 14,
color: fontColor,
fontStyle: FontStyle.italic,
);
const mediumTextStyle = TextStyle(
fontFamily: 'Arial',
fontSize: 14,
fontWeight: FontWeight.w500,
color: fontColor,
);
const semiBoldTextStyle = TextStyle(
fontFamily: 'Arial',
fontSize: 14,
fontWeight: FontWeight.w600,
color: fontColor,
);
const boldTextStyle = TextStyle(
fontFamily: 'Arial',
fontSize: 14,
fontWeight: FontWeight.w700,
color: fontColor,
);
const extraBoldTextStyle = TextStyle(
fontFamily: 'Arial',
fontSize: 14,
fontWeight: FontWeight.w800,
color: fontColor,
);

124
lib/app/themes/app_theme.dart Executable file
View File

@ -0,0 +1,124 @@
import 'package:flutter/material.dart';
import 'app_colors.dart';
import 'app_text.dart';
ThemeData appTheme = ThemeData(
useMaterial3: true,
primaryColor: mainColor,
scaffoldBackgroundColor: Colors.white,
canvasColor: Colors.white,
fontFamily: 'Poppins',
appBarTheme: AppBarTheme(
elevation: 0,
titleTextStyle: boldTextStyle.copyWith(fontSize: 16, color: fontGrey),
centerTitle: true,
),
textTheme: TextTheme(
displayLarge: regularTextStyle.copyWith(fontSize: 32),
displayMedium: regularTextStyle.copyWith(fontSize: 20),
displaySmall: regularTextStyle.copyWith(fontSize: 18),
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
backgroundColor: mainColor,
foregroundColor: Colors.white,
disabledBackgroundColor: mainColor.withOpacity(.3),
minimumSize: const Size(double.maxFinite, 58),
textStyle: boldTextStyle,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
shadowColor: Colors.transparent,
elevation: 0,
),
),
outlinedButtonTheme: OutlinedButtonThemeData(
style: OutlinedButton.styleFrom(
textStyle: boldTextStyle,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
side: const BorderSide(
color: mainColor,
width: 1,
),
foregroundColor: mainColor,
// disabledForegroundColor: mainColor.withOpacity(.3),
minimumSize: const Size(double.maxFinite, 58),
),
),
textButtonTheme: TextButtonThemeData(
style: TextButton.styleFrom(
foregroundColor: mainColor,
disabledForegroundColor: mainColor.withOpacity(.3),
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
textStyle: semiBoldTextStyle,
shadowColor: Colors.transparent,
),
),
iconTheme: const IconThemeData(
color: mainColor,
),
listTileTheme: ListTileThemeData(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
checkboxTheme: CheckboxThemeData(
fillColor: MaterialStateProperty.all(mainColor),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(4),
),
side: const BorderSide(
color: secondaryGrey,
width: 1,
),
),
radioTheme: RadioThemeData(
fillColor: MaterialStateProperty.all(mainColor),
),
tabBarTheme: TabBarTheme(
labelColor: mainColor,
unselectedLabelColor: secondaryGrey,
labelStyle: boldTextStyle.copyWith(fontSize: 16),
unselectedLabelStyle: mediumTextStyle.copyWith(fontSize: 16),
),
chipTheme: ChipThemeData(
backgroundColor: Colors.white,
disabledColor: Colors.white,
selectedColor: Colors.white,
secondarySelectedColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
side: const BorderSide(color: fifthGrey),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6),
),
labelStyle: regularTextStyle.copyWith(fontSize: 12, color: fontGrey),
secondaryLabelStyle:
regularTextStyle.copyWith(fontSize: 12, color: secondaryColor),
deleteIconColor: fontGrey,
showCheckmark: false,
),
popupMenuTheme: PopupMenuThemeData(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
side: const BorderSide(
color: fifthGrey,
width: 1,
),
),
),
colorScheme: const ColorScheme.light(
primary: mainColor,
secondary: secondaryColor,
onPrimary: Colors.white,
onSecondary: Colors.white,
error: dangerColor,
onError: dangerColor,
background: backgroundColor,
).copyWith(background: Colors.white),
);

56
lib/main.dart Normal file
View File

@ -0,0 +1,56 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'package:stacked_services/stacked_services.dart';
import 'app/app.locator.dart';
import 'app/app.router.dart';
import 'app/setup_snackbar_ui.dart';
import 'app/themes/app_theme.dart';
Future main() async {
await initializeDateFormatting('id_ID');
WidgetsFlutterBinding.ensureInitialized();
HttpOverrides.global = MyHttpOverrides();
await dotenv.load(fileName: ".env");
await setupAllLocator();
runApp(const MyApp());
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Electric Monitoring',
theme: appTheme,
debugShowCheckedModeBanner: false,
navigatorKey: StackedService.navigatorKey,
onGenerateRoute: StackedRouter().onGenerateRoute,
builder: EasyLoading.init(),
// home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
Future<void> setupAllLocator() async {
await setupLocator();
// setupDialogUi();
// setupBottomSheetUi();
setupSnackbarUi();
}
class MyHttpOverrides extends HttpOverrides {
@override
HttpClient createHttpClient(SecurityContext? context) {
return super.createHttpClient(context)
..badCertificateCallback =
(X509Certificate cert, String host, int port) => true;
}
}

28
lib/model/data_model.dart Normal file
View File

@ -0,0 +1,28 @@
import '../app/app.locator.dart';
import '../services/other_function.dart';
class DataModel {
final _myFunction = locator<OtherFunction>();
int? no;
String? waterHeight;
int? status;
String? createdAt;
DataModel({this.no, this.waterHeight, this.status, this.createdAt});
DataModel.fromJson(Map<String, dynamic> json) {
no = json['no'];
waterHeight = json['water_height'];
status = json['status'];
createdAt = _myFunction.formatDateString2(json['created_at']);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['no'] = no;
data['water_height'] = waterHeight;
data['status'] = status;
data['created_at'] = createdAt;
return data;
}
}

View File

@ -0,0 +1,57 @@
import 'package:intl/intl.dart';
class OntDataModel {
final int idData;
final int id;
final DateTime waktu; // Use DateTime instead of String
final String status;
final String download;
final String upload;
OntDataModel({
required this.idData,
required this.id,
required this.waktu,
required this.status,
required this.download,
required this.upload,
});
// Factory constructor to create an instance from JSON
factory OntDataModel.fromJson(Map<String, dynamic> json) {
DateTime originalTime =
DateTime.parse(json['waktu'].toString()).toUtc(); // Ensure UTC
DateTime utcPlus8 =
originalTime.add(const Duration(hours: 8)); // Convert to UTC+8
return OntDataModel(
idData: json['id_data'] is int
? json['id_data']
: int.tryParse(json['id_data'].toString()) ?? 0,
id: json['id'] is int
? json['id']
: int.tryParse(json['id'].toString()) ?? 0,
waktu: utcPlus8, // Store UTC+8 time
status: json['status']?.toString() ?? 'Unknown',
download: json['download']?.toString() ?? '-',
upload: json['upload']?.toString() ?? '-',
);
}
// Method to return formatted UTC+8 date
String getFormattedDate() {
return DateFormat('yyyy-MM-dd HH:mm:ss').format(waktu);
}
// Convert back to UTC before saving to JSON
Map<String, dynamic> toJson() => {
'id_data': idData,
'id': id,
'waktu': waktu
.subtract(const Duration(hours: 8))
.toIso8601String(), // Convert back to original UTC
'status': status,
'download': download,
'upload': upload,
};
}

63
lib/model/ont_model.dart Normal file
View File

@ -0,0 +1,63 @@
import 'package:intl/intl.dart';
class OntModel {
int? id;
String? nama;
String? noInternet;
String? noHp;
String? alamat;
String? langganan;
String? download;
String? upload;
String? status;
DateTime? updated;
OntModel({
this.id,
this.nama,
this.noInternet,
this.noHp,
this.alamat,
this.langganan,
this.download,
this.upload,
this.status,
this.updated,
});
factory OntModel.fromJson(Map<String, dynamic> json) {
DateTime originalTime =
DateTime.parse(json['updated'].toString()).toUtc(); // Ensure UTC
DateTime utcPlus8 =
originalTime.add(const Duration(hours: 8)); // Convert to UTC+8
return OntModel(
id: json['id'] as int?,
nama: json['nama'] as String?,
noInternet: json['no_internet'] as String?,
noHp: json['no_hp'] as String?,
alamat: json['alamat'] as String?,
langganan: json['langganan'] as String?,
download: json['download'] as String?,
upload: json['upload'] as String?,
status: json['status'] as String?,
updated: utcPlus8,
);
}
String getFormattedDate() {
return DateFormat('yyyy-MM-dd HH:mm:ss').format(updated!);
}
Map<String, dynamic> toJson() => {
'id': id,
'nama': nama,
'no_internet': noInternet,
'no_hp': noHp,
'alamat': alamat,
'langganan': langganan,
'download': download,
'upload': upload,
'status': status,
'updated': updated?.toIso8601String(),
};
}

View File

@ -0,0 +1,107 @@
import 'package:dio/dio.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:stacked_services/stacked_services.dart';
import '../app/app.locator.dart';
import '../app/app.logger.dart';
class MyHttpServices {
final _log = getLogger('MyHttpServices');
final _snackbarService = locator<SnackbarService>();
final _options = BaseOptions(
baseUrl: dotenv.env['api_url']!,
connectTimeout: const Duration(seconds: 120),
receiveTimeout: const Duration(seconds: 120),
);
late Dio _dio;
MyHttpServices() {
_dio = Dio(_options);
}
Future<Response> get(String path, {bool stat = true}) async {
try {
return await _dio.get(path);
} on DioException catch (e) {
_log.e(e.response!.statusCode!);
String response = e.response!.statusCode! < 500
? e.response!.data['message'].toString()
: e.response!.statusMessage.toString();
_log.e('ini errornya: $response');
if (stat) {
_snackbarService.showSnackbar(
message: response,
title: 'Error',
duration: const Duration(milliseconds: 1000),
);
}
rethrow;
}
}
Future<Response> postWithFormData(String path, FormData formData,
{bool stat = true}) async {
_log.wtf('path: $path');
try {
return await _dio.post(path, data: formData);
} on DioException catch (e) {
_log.e(e.response!.statusCode!);
String response = e.response!.statusCode! < 500
? e.response!.data['message'].toString()
: e.response!.statusMessage.toString();
_log.e('ini errornya: $response');
if (stat) {
_snackbarService.showSnackbar(
message: response,
title: 'Error',
duration: const Duration(milliseconds: 1000),
);
}
rethrow;
}
}
// putWithFormData
Future<Response> putWithFormData(String path, FormData formData,
{bool stat = true}) async {
try {
return await _dio.put(path, data: formData);
} on DioException catch (e) {
_log.e(e.response!.statusCode!);
String response = e.response!.statusCode! < 500
? e.response!.data['message'].toString()
: e.response!.statusMessage.toString();
_log.e('ini errornya: $response');
if (stat) {
_snackbarService.showSnackbar(
message: response,
title: 'Error',
duration: const Duration(milliseconds: 1000),
);
}
rethrow;
}
}
// // delete
// Future<Response> delete(String path, FormData data) async {
// try {
// // log.i('path: $path');
// return await _dio.delete(
// path,
// data: data,
// // encoding: Encoding.getByName('utf-8'),
// options: Options(
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded',
// },
// ),
// );
// } on DioError catch (e) {
// log.e(e.message);
// log.e(e.response);
// rethrow;
// }
// }
}

View File

@ -0,0 +1,39 @@
import 'package:flutter_easyloading/flutter_easyloading.dart';
class MyEasyLoading {
showLoading() {
EasyLoading.show(
status: 'loading...',
maskType: EasyLoadingMaskType.black,
dismissOnTap: false,
);
}
dismiss() {
EasyLoading.dismiss();
}
customLoading(String message) {
EasyLoading.show(
status: message,
maskType: EasyLoadingMaskType.black,
dismissOnTap: false,
);
}
showSuccess(String message) {
EasyLoading.showSuccess(message);
}
showError(String message) {
EasyLoading.showError(message);
}
showInfo(String message) {
EasyLoading.showInfo(message);
}
showProgress(double progress, String status) {
EasyLoading.showProgress(progress, status: status);
}
}

View File

@ -0,0 +1,42 @@
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class MyNotification {
static Future initialize(
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin) async {
var androidInitialize =
const AndroidInitializationSettings('mipmap/ic_launcher');
var iOSInitialize = const DarwinInitializationSettings();
var initializeSettings =
InitializationSettings(android: androidInitialize, iOS: iOSInitialize);
await flutterLocalNotificationsPlugin.initialize(initializeSettings);
}
Future showNotification(
{var id = 0,
var title,
var body,
var payload,
required FlutterLocalNotificationsPlugin
flutterLocalNotificationsPlugin}) async {
AndroidNotificationDetails androidPlatformChannelSpecifics =
const AndroidNotificationDetails(
'07eff3c8-e3d7-4386-b8a1-e6588cd9fbb5', // channelId
'channel_name',
sound: RawResourceAndroidNotificationSound('notification_fuck'),
importance: Importance.max,
priority: Priority.high,
);
var iOSPlatformChannelSpecifics = const DarwinNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics,
iOS: iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
id,
title,
body,
platformChannelSpecifics,
payload: payload,
);
}
}

View File

@ -0,0 +1,25 @@
import 'package:shared_preferences/shared_preferences.dart';
class MySharedPrefs {
final Future<SharedPreferences> prefs = SharedPreferences.getInstance();
Future<String?> getString(String key) async {
final SharedPreferences prefs = await this.prefs;
return prefs.getString(key);
}
Future<bool> setString(String key, String value) async {
final SharedPreferences prefs = await this.prefs;
return prefs.setString(key, value);
}
Future<bool> removeString(String key) async {
final SharedPreferences prefs = await this.prefs;
return prefs.remove(key);
}
Future<bool> clear() async {
final SharedPreferences prefs = await this.prefs;
return prefs.clear();
}
}

View File

@ -0,0 +1,54 @@
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:socket_io_client/socket_io_client.dart';
import '../app/app.logger.dart';
class MySocketIoClient {
final log = getLogger('MySocketIoClient');
final String _url = dotenv.env['url']!;
double waterHeight = 0;
int warningLevel = 0;
int dangerLevel = 0;
String status = '...';
static final MySocketIoClient _instance = MySocketIoClient._internal();
factory MySocketIoClient() => _instance;
MySocketIoClient._internal();
int notif = 0;
late Socket _socket;
Socket get socket => _socket;
Future<void> init() async {
try {
_socket = io(_url, <String, dynamic>{
'transports': ['websocket'],
'autoConnect': false,
});
_socket.connect();
log.i('socket connected');
} catch (e) {
log.e('error : $e');
}
}
Future<void> emit(String event, dynamic data) async {
_socket.emit(event, data);
}
Future<void> on(String event, Function(dynamic) callback) async {
_socket.on(event, callback);
}
Future<void> off(String event) async {
_socket.off(event);
}
Future<void> disconnect() async {
_socket.disconnect();
}
Future<void> connect() async {
_socket.connect();
}
}

View File

@ -0,0 +1,150 @@
import 'package:intl/intl.dart';
import 'package:ont_app2/model/ont_data_model.dart';
import 'package:ont_app2/model/ont_model.dart';
class OtherFunction {
List<OntDataModel> listDataOnt = [];
OntModel? ontModel;
int umur(String tanggalLahir) {
// change tanggalLahir to DateTime
DateTime date = DateTime.parse(tanggalLahir);
// get current date
DateTime now = DateTime.now();
// get difference in year
int year = now.year - date.year;
return year;
}
String commaFormat(int number) {
final formatter = NumberFormat('#,###');
return formatter.format(number);
}
String changeMonth(String month) {
switch (month) {
case 'Januari':
return '01';
case 'Februari':
return '02';
case 'Maret':
return '03';
case 'April':
return '04';
case 'Mei':
return '05';
case 'Juni':
return '06';
case 'Juli':
return '07';
case 'Agustus':
return '08';
case 'September':
return '09';
case 'Oktober':
return '10';
case 'November':
return '11';
case 'Desember':
return '12';
default:
return '';
}
}
String changeMonthYear(String s) {
// get the last 2 digits
String month = s.substring(s.length - 2);
// get the first 4 digits
String year = s.substring(0, 4);
// return the month and year
switch (month) {
case '01':
return 'Januari $year';
case '02':
return 'Februari $year';
case '03':
return 'Maret $year';
case '04':
return 'April $year';
case '05':
return 'Mei $year';
case '06':
return 'Juni $year';
case '07':
return 'Juli $year';
case '08':
return 'Agustus $year';
case '09':
return 'September $year';
case '10':
return 'Oktober $year';
case '11':
return 'November $year';
case '12':
return 'Desember $year';
default:
return '';
}
}
String getDayOfWeek(String date) {
DateTime dateTime = DateTime.parse(date);
List<String> daysOfWeek = [
'Senin',
'Selasa',
'Rabu',
'Kamis',
'Jumat',
'Sabtu',
'Minggu'
];
return daysOfWeek[dateTime.weekday - 1];
}
String formatDateString(String dateString) {
// Remove the "T" and replace it with " | "
String formattedString = dateString.replaceAll('T', '\n');
// Remove the ".000Z"
formattedString = formattedString.replaceAll('.000Z', '');
// Parse the input string to DateTime object
DateTime dateTime = DateTime.parse(dateString);
// Get the day of the week in Indonesian
String dayOfWeek = DateFormat.EEEE('id_ID').format(dateTime);
// Add the day of the week to the formatted string
formattedString = '$formattedString\n$dayOfWeek';
return formattedString;
}
String formatDateString2(String dateString) {
DateTime dateTime = DateTime.parse(dateString);
// Adjust for the timezone if needed (this example assumes UTC)
dateTime = dateTime.toLocal();
// Format the DateTime object to match your database format
String dbDate = DateFormat('yyyy-MM-dd HH:mm:ss').format(dateTime);
return dbDate;
}
String timeNameRemover(String time) {
List<String> parts = time.split(' ');
String timePart = parts[0];
// Split the time part into hours, minutes, and seconds
List<String> timeComponents = timePart.split(':');
String hours = timeComponents[0];
String minutes = timeComponents[1];
// Create the new time string without seconds and with a period instead of a colon
String newTimeStr = '$hours.$minutes';
return newTimeStr;
}
}

View File

@ -0,0 +1,91 @@
import 'package:flutter/material.dart';
import 'package:ont_app2/ui/widgets/my_button.dart';
import 'package:stacked/stacked.dart';
import 'package:validatorless/validatorless.dart';
import '../../widgets/my_textformfield.dart';
import './login_view_model.dart';
class LoginView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ViewModelBuilder<LoginViewModel>.reactive(
viewModelBuilder: () => LoginViewModel(),
onViewModelReady: (LoginViewModel model) async {
await model.init();
},
builder: (
BuildContext context,
LoginViewModel model,
Widget? child,
) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(20),
child: Center(
child: SingleChildScrollView(
child: Form(
key: model.formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Image(
image: AssetImage("assets/logo1.png"),
width: 200,
height: 200,
),
const Text(
"Silahkan Login",
),
const SizedBox(height: 20),
MyTextFormField(
controller: model.nomorInternetController,
labelText: "Nomor Internet",
hintText: "Masukkan Nomor Internet",
prefixIcon: const Icon(
Icons.phone,
),
validator: Validatorless.multiple(
[
Validatorless.required("Masukkan Nomor Internet"),
Validatorless.min(
12, "Nomor Internet harus 12 angka"),
Validatorless.number(
"Nomor Internet harus berupa angka"),
],
),
keyboardType: TextInputType.number,
maxLength: 12,
),
const SizedBox(height: 20),
MyTextFormField(
controller: model.passwordController,
labelText: "Password",
hintText: "Masukkan Password",
obscureText: true,
prefixIcon: const Icon(
Icons.lock,
),
validator: Validatorless.required("Masukkan Password"),
),
const SizedBox(height: 15),
MyButton(
text: "Login",
onPressed: () {
// if (!model.formKey.currentState!.validate()) {
// return;
// }
model.login();
},
),
],
),
),
),
),
),
);
},
);
}
}

View File

@ -0,0 +1,64 @@
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import '../../../app/app.logger.dart';
import '../../../app/app.router.dart';
import '../../../app/core/custom_base_view_model.dart';
import '../../../app/enum/snackbar_enum.dart';
import '../../../model/ont_model.dart';
class LoginViewModel extends CustomBaseViewModel {
final log = getLogger('LoginViewModel');
// form variable
final formKey = GlobalKey<FormState>();
TextEditingController nomorInternetController = TextEditingController();
TextEditingController passwordController = TextEditingController();
Future<void> init() async {}
login() async {
log.wtf('login proses');
easyLoading.customLoading("Login...");
setBusy(true);
try {
var formData = FormData.fromMap({
"no_internet": nomorInternetController.text,
"password": passwordController.text,
});
var res = await httpService.postWithFormData(
'login',
formData,
);
// log.wtf(res.statusCode);
if (res.statusCode == 200) {
// log.wtf(res.data["data"]['id']);
OntModel ontModel = OntModel.fromJson(res.data["data"]);
otherFunction.ontModel = ontModel;
await mySharedPrefs.setString('id', ontModel.id.toString());
// log.wtf(await mySharedPrefs.getString('id'));
// log.wtf(ontModel.toJson());
// snackbarService.showCustomSnackBar(
// message: "Login Berhasil",
// variant: SnackbarType.sukses,
// duration: const Duration(milliseconds: 2000),
// );
// await 2 seconds
// await Future.delayed(const Duration(seconds: 2));
navigationService.replaceWith(Routes.navBarView);
snackbarService.showCustomSnackBar(
message: "Login Berhasil",
variant: SnackbarType.sukses,
duration: const Duration(milliseconds: 10000),
);
}
} catch (e) {
return;
} finally {
setBusy(false);
easyLoading.dismiss();
}
}
}

View File

@ -0,0 +1,152 @@
import 'package:flutter/material.dart';
import 'package:stacked/stacked.dart';
import '../../../../app/themes/app_text.dart';
import './log_data_view_model.dart';
class LogDataView extends StatelessWidget {
const LogDataView({super.key});
@override
Widget build(BuildContext context) {
return ViewModelBuilder<LogDataViewModel>.reactive(
viewModelBuilder: () => LogDataViewModel(),
onViewModelReady: (LogDataViewModel model) async {
await model.init();
},
fireOnViewModelReadyOnce: true,
createNewViewModelOnInsert: true,
builder: (
BuildContext context,
LogDataViewModel model,
Widget? child,
) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(30),
child: model.isBusy
? const Center(
child: CircularProgressIndicator(),
)
: SingleChildScrollView(
child: Table(
border: TableBorder.all(),
children: [
const TableRow(
children: [
TableCell(
child: Center(
child: Text(
'Waktu',
style: boldTextStyle,
),
),
),
TableCell(
child: Center(
child: Text(
'Status',
style: boldTextStyle,
),
),
),
TableCell(
child: Center(
child: Text(
'Download',
style: boldTextStyle,
),
),
),
TableCell(
child: Center(
child: Text(
'Upload',
style: boldTextStyle,
),
),
),
],
),
...model.otherFunction.listDataOnt.isEmpty
? [
TableRow(
children: List.generate(
4, // Ensure the same number of columns
(index) => TableCell(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 10),
child: Text(
"Loading...",
style: regularTextStyle,
textAlign: TextAlign.center,
),
),
),
),
),
]
: model.otherFunction.listDataOnt
.map((data) => TableRow(
children: [
TableCell(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 10),
child: Text(
data.getFormattedDate(),
style: regularTextStyle,
textAlign: TextAlign.center,
),
),
),
TableCell(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 10),
child: Text(
data.status,
style: regularTextStyle,
textAlign: TextAlign.center,
),
),
),
TableCell(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 10),
child: Text(
data.download == "-"
? "-"
: data.download + " Mbps",
style: regularTextStyle,
textAlign: TextAlign.center,
),
),
),
TableCell(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 10),
child: Text(
data.upload == "-"
? "-"
: data.upload + " Mbps",
style: regularTextStyle,
textAlign: TextAlign.center,
),
),
),
],
))
.toList(),
],
),
),
),
);
},
);
}
}

View File

@ -0,0 +1,15 @@
import 'dart:async';
import '../../../../app/app.logger.dart';
import '../../../../app/core/custom_base_view_model.dart';
class LogDataViewModel extends CustomBaseViewModel {
final log = getLogger('LogDataViewModel');
Future<void> init() async {
Timer.periodic(const Duration(seconds: 10), (timer) {
log.i('timer dan refresh data');
notifyListeners();
});
}
}

View File

@ -0,0 +1,137 @@
import 'package:flutter/material.dart';
import 'package:stacked/stacked.dart';
import '../../../../app/themes/app_colors.dart';
import '../../../../app/themes/app_text.dart';
import './monitoring_view_model.dart';
class MonitoringView extends StatelessWidget {
const MonitoringView({super.key});
@override
Widget build(BuildContext context) {
return ViewModelBuilder<MonitoringViewModel>.reactive(
viewModelBuilder: () => MonitoringViewModel(),
onViewModelReady: (MonitoringViewModel model) async {
await model.init();
},
fireOnViewModelReadyOnce: true,
createNewViewModelOnInsert: true,
builder: (
BuildContext context,
MonitoringViewModel model,
Widget? child,
) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(30),
child: Center(
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
"Monitoring Router",
style: boldTextStyle.copyWith(fontSize: 30),
),
const SizedBox(height: 20),
const Image(
image: AssetImage("assets/logo.png"),
width: 125,
height: 125,
),
const SizedBox(height: 20),
Container(
padding: const EdgeInsets.all(20),
width: double.infinity,
decoration: BoxDecoration(
color: mainColor,
borderRadius: BorderRadius.circular(10.0),
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TheText(
title: 'Nama',
text: model.otherFunction.ontModel!.nama!,
),
TheText(
title: 'No Internet',
text: model.otherFunction.ontModel!.noInternet!,
),
TheText(
title: 'No Telpon',
text: model.otherFunction.ontModel!.noHp!,
),
TheText(
title: 'Alamat',
text: model.otherFunction.ontModel!.alamat!,
),
TheText(
title: 'Paket',
text: model.otherFunction.ontModel!.langganan!,
),
TheText(
title: 'Status',
text: model.otherFunction.ontModel!.status!,
),
TheText(
title: 'Speed',
// text: "0.04 Mbps Down/0.03Mbps Up",
text:
"${model.otherFunction.ontModel!.download!} Mbps Down/${model.otherFunction.ontModel!.upload!} Mbps Up",
),
TheText(
title: 'Last Updated',
// text: "2023-01-01 00:00:00",
text: model.otherFunction.ontModel!
.getFormattedDate(),
),
],
),
),
],
),
),
),
),
);
},
);
}
}
class TheText extends StatelessWidget {
const TheText({
super.key,
required this.title,
required this.text,
});
final String title;
final String text;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 10),
child: RichText(
text: TextSpan(
text: '$title : ',
style: boldTextStyle.copyWith(
color: lightColor,
),
children: [
TextSpan(
text: text,
style: regularTextStyle.copyWith(
color: lightColor,
),
),
],
),
),
);
}
}

View File

@ -0,0 +1,15 @@
import 'dart:async';
import '../../../../app/app.logger.dart';
import '../../../../app/core/custom_base_view_model.dart';
class MonitoringViewModel extends CustomBaseViewModel {
final log = getLogger('MonitoringViewModel');
Future<void> init() async {
Timer.periodic(const Duration(seconds: 5), (timer) {
log.i('timer dan refresh data');
notifyListeners();
});
}
}

View File

@ -0,0 +1,81 @@
import 'package:flutter/material.dart';
import 'package:stacked/stacked.dart';
import 'package:stacked_services/stacked_services.dart';
import 'package:stylish_bottom_bar/stylish_bottom_bar.dart';
import '../../../app/app.router.dart';
import '../../../app/themes/app_colors.dart';
import '../../../app/themes/app_text.dart';
import './nav_bar_view_model.dart';
class NavBarView extends StatelessWidget {
const NavBarView({super.key});
@override
Widget build(BuildContext context) {
return ViewModelBuilder<NavBarViewModel>.reactive(
viewModelBuilder: () => NavBarViewModel(),
onViewModelReady: (NavBarViewModel model) async {
await model.init();
},
builder: (
BuildContext context,
NavBarViewModel model,
Widget? child,
) {
return PopScope(
canPop: false,
child: Scaffold(
appBar: AppBar(
backgroundColor: mainColor,
title: Text(
model.bottomNavBarList[model.currentIndex]['name'],
style: boldTextStyle.copyWith(color: fifthGrey),
),
),
body: ExtendedNavigator(
navigatorKey: StackedService.nestedNavigationKey(3),
router: NavBarViewRouter(),
initialRoute: NavBarViewRoutes.monitoringView,
),
bottomNavigationBar: StylishBottomBar(
items: [
for (var item in model.bottomNavBarList)
BottomBarItem(
icon: Icon(item['icon'],
color: model.currentIndex ==
model.bottomNavBarList.indexOf(item)
? fifthGrey
: backgroundColor),
title: Text(
item['name'],
style: regularTextStyle.copyWith(
color: model.currentIndex ==
model.bottomNavBarList.indexOf(item)
? fifthGrey
: mainGrey,
),
),
backgroundColor: model.currentIndex ==
model.bottomNavBarList.indexOf(item)
? fontColor
: mainGrey,
),
],
currentIndex: model.currentIndex,
hasNotch: true,
backgroundColor: mainColor,
onTap: (value) {
model.handleNavigation(value);
},
option: BubbleBarOptions(
barStyle: BubbleBarStyle.horizontal,
bubbleFillStyle: BubbleFillStyle.fill,
opacity: 0.3),
),
),
);
},
);
}
}

View File

@ -0,0 +1,158 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:ont_app2/model/ont_data_model.dart';
import 'package:ont_app2/model/ont_model.dart';
import 'package:stacked/stacked.dart';
import 'package:stacked_services/stacked_services.dart';
import '../../../app/app.locator.dart';
import '../../../app/app.logger.dart';
import '../../../app/app.router.dart';
import '../../../services/http_services.dart';
import '../../../services/my_notification.dart';
import '../../../services/my_preferences.dart';
import '../../../services/my_socket_io_client.dart';
import '../../../services/other_function.dart';
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
class NavBarViewModel extends IndexTrackingViewModel {
final log = getLogger('NavBarViewModel');
final _navigationService = locator<NavigationService>();
final _mySharedPrefs = locator<MySharedPrefs>();
final _socketIoClient = locator<MySocketIoClient>();
final _myNotification = locator<MyNotification>();
final _otherFunction = locator<OtherFunction>();
final _httpServices = locator<MyHttpServices>();
final _bottomNavBarList = [
{
'name': 'Monitoring',
'icon': Icons.home_outlined,
},
{
'name': 'Log Data',
'icon': Icons.list_alt_outlined,
},
];
List<Map<String, dynamic>> get bottomNavBarList => _bottomNavBarList;
final List<String> _views = [
NavBarViewRoutes.monitoringView,
NavBarViewRoutes.logDataView,
];
Future<void> init() async {
String? id = await _mySharedPrefs.getString('id');
refreshData(id!);
Timer.periodic(const Duration(seconds: 10), (timer) {
log.i('timer dan refresh data');
refreshData(id);
refreshOnt(id);
});
// _socketIoClient.on('data', (data) {
// // log.i('data : $data');
// var waterHeight = data['water_height'];
// _socketIoClient.waterHeight = waterHeight is int
// ? waterHeight.toDouble()
// : waterHeight is double
// ? waterHeight
// : double.parse(waterHeight as String);
// _socketIoClient.warningLevel = data['warning_level'];
// _socketIoClient.dangerLevel = data['danger_level'];
// if (_socketIoClient.dangerLevel == 1) {
// _socketIoClient.status =
// "Bahaya , Peringatan Banjir, Air Melewati Batas";
// if (_socketIoClient.notif < 2) {
// _myNotification.showNotification(
// id: 1,
// title: 'Peringatan Banjir',
// body: 'Air Melewati Batas',
// payload: 'payload',
// flutterLocalNotificationsPlugin: flutterLocalNotificationsPlugin,
// );
// _socketIoClient.notif = 2;
// }
// } else if (_socketIoClient.warningLevel == 1) {
// _socketIoClient.status =
// "Peringatan Banjir, Air Dalam Skala 4:5 atau lebih";
// if (_socketIoClient.notif == 0) {
// _myNotification.showNotification(
// id: 2,
// title: 'Peringatan Banjir',
// body: 'Air Dalam Skala 4:5 atau lebih',
// payload: 'payload',
// flutterLocalNotificationsPlugin: flutterLocalNotificationsPlugin,
// );
// _socketIoClient.notif = 1;
// }
// } else {
// _socketIoClient.status = "Normal";
// _socketIoClient.notif = 0;
// }
// notifyListeners();
// });
}
refreshData(String id) async {
log.wtf("lakukan pengambilan data");
setBusy(true);
try {
var res = await _httpServices.get('/data_ont?id=$id', stat: false);
List<Map<String, dynamic>> data =
List<Map<String, dynamic>>.from(res.data);
List<OntDataModel> dataModel =
data.map((e) => OntDataModel.fromJson(e)).toList();
_otherFunction.listDataOnt.clear();
_otherFunction.listDataOnt = dataModel;
for (var i = 0; i < dataModel.length; i++) {
log.i(dataModel[i].toJson());
}
notifyListeners();
} catch (e) {
log.e(e);
} finally {
setBusy(false);
}
}
refreshOnt(String id) async {
log.wtf("lakukan pengambilan data ont");
setBusy(true);
try {
var res = await _httpServices.get('/data-ont/$id', stat: false);
log.wtf(res.data);
OntModel data = OntModel.fromJson(res.data);
_otherFunction.ontModel = data;
notifyListeners();
} catch (e) {
log.e(e);
log.e("Disini yang error");
} finally {
setBusy(false);
}
}
void handleNavigation(int index) {
log.d("handleNavigation: $index");
log.d("currentIndex: $currentIndex");
if (currentIndex == index) return;
setIndex(index);
// header = _bottomNavBarList[index]['header'] as String;
_navigationService.navigateTo(
_views[index],
id: 3,
);
}
}

View File

@ -0,0 +1,61 @@
import 'package:flutter/material.dart';
import 'package:stacked/stacked.dart';
import '../../../app/themes/app_text.dart';
import './splash_screen_view_model.dart';
class SplashScreenView extends StatelessWidget {
const SplashScreenView({super.key});
@override
Widget build(BuildContext context) {
return ViewModelBuilder<SplashScreenViewModel>.nonReactive(
viewModelBuilder: () => SplashScreenViewModel(),
onViewModelReady: (SplashScreenViewModel model) async {
await model.init();
},
builder: (
BuildContext context,
SplashScreenViewModel model,
Widget? child,
) {
return Scaffold(
// backgroundColor: mainColor,
body: Column(
children: [
const SizedBox(),
Expanded(
child: Center(
// show the logo.png
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Image(
image: AssetImage("assets/logo1.png"),
width: 200,
height: 200,
),
const SizedBox(height: 10),
Text(
"Monitoring Indihome Router",
style: boldTextStyle.copyWith(
fontSize: 20,
),
)
],
),
),
),
const Text(
"Made with Flutter and Passion By Febri",
textAlign: TextAlign.center,
style: regularTextStyle,
),
const SizedBox(height: 15),
],
),
);
},
);
}
}

View File

@ -0,0 +1,23 @@
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import '../../../app/app.logger.dart';
import '../../../app/app.router.dart';
import '../../../app/core/custom_base_view_model.dart';
import '../../../services/my_notification.dart';
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
class SplashScreenViewModel extends CustomBaseViewModel {
final log = getLogger('SplashScreenViewModel');
Future<void> init() async {
await Future.delayed(const Duration(seconds: 2));
// navigate to login page
// ignore: use_build_context_synchronously
MyNotification.initialize(flutterLocalNotificationsPlugin);
socketIoClient.init();
// socketIoClient.connect();
navigationService.replaceWith(Routes.loginView);
}
}

View File

@ -0,0 +1,34 @@
import 'package:flutter/material.dart';
import '../../app/themes/app_colors.dart';
class MyButton extends StatelessWidget {
const MyButton({
Key? key,
required this.text,
this.onPressed,
}) : super(key: key);
final String text;
final VoidCallback? onPressed;
@override
Widget build(BuildContext context) {
return ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: mainColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30),
),
),
onPressed: onPressed,
child: Text(
text,
style: const TextStyle(
color: backgroundColor,
fontSize: 18,
),
),
);
}
}

View File

@ -0,0 +1,91 @@
import 'package:flutter/material.dart';
import '../../app/themes/app_colors.dart';
class MyTextFormField extends StatelessWidget {
const MyTextFormField({
Key? key,
this.labelText,
this.hintText,
this.obscureText,
this.validator,
this.suffixIcon,
this.prefixIcon,
this.focusNode,
this.controller,
this.maxLines = 1,
this.onEditingComplete,
this.readOnly = false,
this.onTap,
this.keyboardType = TextInputType.text,
this.initialValue,
this.enabled = true,
this.maxLength,
}) : super(key: key);
final String? labelText;
final String? hintText;
final bool? obscureText;
final FormFieldValidator<String>? validator;
final Widget? suffixIcon;
final Widget? prefixIcon;
final FocusNode? focusNode;
final TextEditingController? controller;
final int maxLines;
final VoidCallback? onEditingComplete;
final bool readOnly;
final VoidCallback? onTap;
final TextInputType keyboardType;
final String? initialValue;
final bool enabled;
final int? maxLength;
@override
Widget build(BuildContext context) {
return TextFormField(
maxLength: maxLength,
enabled: enabled,
initialValue: initialValue,
onEditingComplete: onEditingComplete,
maxLines: maxLines,
controller: controller,
focusNode: focusNode,
obscureText: obscureText ?? false,
readOnly: readOnly,
onTap: onTap,
keyboardType: keyboardType,
decoration: InputDecoration(
prefixIcon: prefixIcon,
suffixIcon: suffixIcon,
enabledBorder: const OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(25)),
borderSide: BorderSide(
color: mainColor,
),
),
focusedBorder: const OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(25)),
borderSide: BorderSide(
color: mainColor,
),
),
focusedErrorBorder: const OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(25)),
borderSide: BorderSide(
color: dangerColor,
),
),
errorBorder: const OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(25)),
borderSide: BorderSide(
color: dangerColor,
),
),
labelText: labelText,
hintText: hintText,
labelStyle: const TextStyle(color: fontColor),
),
validator: validator,
);
}
}