update(MainScreen): Fix Timer cannot cancel when switching tabs

This commit is contained in:
anhtunz
2025-06-23 16:10:36 +07:00
parent bd73ba1b45
commit e6c536f380
8 changed files with 392 additions and 374 deletions

View File

@@ -1,13 +1,11 @@
import 'dart:async';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:persistent_bottom_nav_bar/persistent_bottom_nav_bar.dart';
import '../../product/shared/shared_loading_animation.dart';
import '../../product/shared/shared_component_loading_animation.dart';
import '../../product/utils/app_logger_utils.dart';
import 'shared/alert_card.dart';
import 'shared/warning_card.dart';
import '../../product/utils/device_utils.dart';
import 'device_alias_model.dart';
import 'shared/overview_card.dart';
import '../settings/device_notification_settings/device_notification_settings_model.dart';
@@ -18,8 +16,7 @@ import '../../bloc/home_bloc.dart';
import '../../product/base/bloc/base_bloc.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key, required this.persistentTabController});
final PersistentTabController persistentTabController;
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
@@ -27,24 +24,17 @@ class HomeScreen extends StatefulWidget {
class _HomeScreenState extends State<HomeScreen> {
late HomeBloc homeBloc;
APIServices apiServices = APIServices();
Map<String, List<DeviceWithAlias>> allDevicesAliasMap = {};
List<DeviceWithAlias> devices = [];
bool isFunctionCall = false;
Timer? getAllDevicesTimer;
int notificationCount = 0;
Map<String, List<DeviceWithAlias>> ownerDevicesStatus = {};
List<String> ownerDevicesState = [];
@override
void initState() {
super.initState();
homeBloc = BlocProvider.of(context);
getAllDevicesTimer?.cancel();
AppLoggerUtils.debug("Init State HomeScreen");
getOwnerAndJoinedDevices();
const duration = Duration(seconds: 10);
getAllDevicesTimer =
Timer.periodic(duration, (Timer t) => getOwnerAndJoinedDevices());
Timer.periodic(duration, (Timer t) => homeBloc.getOwnerAndJoinedDevices(context));
}
@override
@@ -56,255 +46,200 @@ class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: context.paddingLow,
child: SingleChildScrollView(
child: Column(
children: <Widget>[
Row(
children: [
Text(
appLocalization(context).notification,
style: context.titleMediumTextStyle,
),
SizedBox(width: context.lowValue),
StreamBuilder<int>(
stream: homeBloc.streamCountNotification,
builder: (context, countSnapshot) {
return Text(
"(${countSnapshot.data ?? 0})",
style: context.titleMediumTextStyle,
);
},
)
],
),
SizedBox(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: StreamBuilder<Map<String, List<DeviceWithAlias>>>(
stream: homeBloc.streamOwnerDevicesStatus,
builder: (context, snapshot) {
return AnimatedSwitcher(
duration: context.lowDuration,
transitionBuilder:
(Widget child, Animation<double> animation) {
final offsetAnimation = Tween<Offset>(
begin: const Offset(0.0, 0.2),
end: Offset.zero,
).animate(CurvedAnimation(
parent: animation,
curve: Curves.easeInOut,
));
return FadeTransition(
opacity: animation,
child: SlideTransition(
position: offsetAnimation,
child: child,
),
);
},
child: snapshot.data?['state'] != null ||
snapshot.data?['battery'] != null
? ConstrainedBox(
key: const ValueKey('data'),
constraints: BoxConstraints(
minWidth:
MediaQuery.of(context).size.width),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
if (snapshot.data?['state'] != null)
...snapshot.data!['state']!
.map(
(item) => SizedBox(
width: context.dynamicWidth(0.95),
child: FutureBuilder<Widget>(
future: warningCard(
context, apiServices, item),
builder: (context,
warningCardSnapshot) {
if (warningCardSnapshot
.hasData) {
return warningCardSnapshot
.data!;
} else {
return const SizedBox
.shrink();
}
},
),
),
)
.toList(),
if (snapshot.data?['battery'] != null)
...snapshot.data!['battery']!
.map(
(batteryItem) => SizedBox(
width: context.dynamicWidth(0.95),
child: FutureBuilder<Widget>(
future: notificationCard(
context,
"lowBattery",
appLocalization(context)
.low_battery_message,
batteryItem,
),
builder: (context,
warningCardSnapshot) {
if (warningCardSnapshot
.hasData) {
return warningCardSnapshot
.data!;
} else {
return const SizedBox
.shrink();
}
},
),
),
)
.toList(),
],
),
)
: Padding(
key: const ValueKey('no_data'),
padding: context.paddingMedium,
child: Center(
return StreamBuilder<List<DeviceWithAlias>?>(
stream: homeBloc.streamAliasDevices,
builder: (context, aliasDevicesSnapshot) {
if(aliasDevicesSnapshot.data == null){
homeBloc.getOwnerAndJoinedDevices(context);
return const SharedLoadingAnimation();
}else{
log("Goi else");
homeBloc.getOwnerDeviceState(context, aliasDevicesSnapshot.data ?? []);
homeBloc.getDeviceStatusAliasMap(aliasDevicesSnapshot.data ?? []);
checkSettingDevice(aliasDevicesSnapshot.data ?? []);
return Scaffold(
body: Padding(
padding: context.paddingLow,
child: SingleChildScrollView(
child: Column(
children: <Widget>[
Row(
children: [
Text(
appLocalization(context).notification,
style: context.titleMediumTextStyle,
),
SizedBox(width: context.lowValue),
StreamBuilder<int>(
stream: homeBloc.streamCountNotification,
builder: (context, countSnapshot) {
if(countSnapshot.data == null){
homeBloc.getOwnerDeviceState(context, aliasDevicesSnapshot.data ?? []);
return const Text("0");
} else{
return Text(
"(${countSnapshot.data ?? 0})",
style: context.titleMediumTextStyle,
);
}
},
)
],
),
SizedBox(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: StreamBuilder<Map<String, List<DeviceWithAlias>>>(
stream: homeBloc.streamOwnerDevicesStatus,
builder: (context, ownerDevicesStatusSnapshot) {
if(ownerDevicesStatusSnapshot.data == null){
homeBloc.getOwnerDeviceState(context, aliasDevicesSnapshot.data ?? []);
return const SharedComponentLoadingAnimation();
}else{
return AnimatedSwitcher(
duration: context.lowDuration,
transitionBuilder:
(Widget child, Animation<double> animation) {
final offsetAnimation = Tween<Offset>(
begin: const Offset(0.0, 0.2),
end: Offset.zero,
).animate(CurvedAnimation(
parent: animation,
curve: Curves.easeInOut,
));
return FadeTransition(
opacity: animation,
child: SlideTransition(
position: offsetAnimation,
child: child,
),
);
},
child: ownerDevicesStatusSnapshot.data?['state'] != null ||
ownerDevicesStatusSnapshot.data?['battery'] != null
? ConstrainedBox(
key: const ValueKey('data'),
constraints: BoxConstraints(
minWidth:
MediaQuery.of(context).size.width),
child: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
children: [
const Icon(
Icons.check_circle_outline_rounded,
size: 40,
color: Colors.green,
),
SizedBox(width: context.lowValue),
Text(
appLocalization(context)
.notification_description,
maxLines: 2,
overflow: TextOverflow.ellipsis,
softWrap: true,
textAlign: TextAlign.start,
),
if (ownerDevicesStatusSnapshot.data?['state'] != null)
...ownerDevicesStatusSnapshot.data!['state']!
.map(
(item) => SizedBox(
width: context.dynamicWidth(0.95),
child: FutureBuilder<Widget>(
future: warningCard(
context, apiServices, item),
builder: (context,
warningCardSnapshot) {
if (warningCardSnapshot
.hasData) {
return warningCardSnapshot
.data!;
} else {
return const SizedBox
.shrink();
}
},
),
),
)
.toList(),
if (ownerDevicesStatusSnapshot.data?['battery'] != null)
...ownerDevicesStatusSnapshot.data!['battery']!
.map(
(batteryItem) => SizedBox(
width: context.dynamicWidth(0.95),
child: FutureBuilder<Widget>(
future: notificationCard(
context,
"lowBattery",
appLocalization(context)
.low_battery_message,
batteryItem,
),
builder: (context,
warningCardSnapshot) {
if (warningCardSnapshot
.hasData) {
return warningCardSnapshot
.data!;
} else {
return const SizedBox
.shrink();
}
},
),
),
)
.toList(),
],
),
)
: Padding(
key: const ValueKey('no_data'),
padding: context.paddingMedium,
child: Center(
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
Icons.check_circle_outline_rounded,
size: 40,
color: Colors.green,
),
SizedBox(width: context.lowValue),
Text(
appLocalization(context)
.notification_description,
maxLines: 2,
overflow: TextOverflow.ellipsis,
softWrap: true,
textAlign: TextAlign.start,
),
],
),
),
),
),
);
},
),
);
}
},
),
),
),
StreamBuilder<Map<String, List<DeviceWithAlias>>>(
stream: homeBloc.streamAllDevicesAliasMap,
builder: (context, allDevicesAliasMapSnapshot) {
if(allDevicesAliasMapSnapshot.data == null){
homeBloc.getDeviceStatusAliasMap(aliasDevicesSnapshot.data ?? []);
return const SharedComponentLoadingAnimation();
}else{
final data = allDevicesAliasMapSnapshot.data!;
return OverviewCard(
isOwner: true,
total: data['all']?.length ?? 0,
active: data['online']?.length ?? 0,
inactive: data['offline']?.length ?? 0,
warning: data['warn']?.length ?? 0,
unused: data['not-use']?.length ?? 0,
showUnused: false,
);
}
},
),
],
),
),
StreamBuilder<Map<String, List<DeviceWithAlias>>>(
stream: homeBloc.streamAllDevicesAliasMap,
builder: (context, allDevicesAliasMapSnapshot) {
if(allDevicesAliasMapSnapshot.data == null){
return const SharedComponentLoadingAnimation();
}else{
final data = allDevicesAliasMapSnapshot.data!;
return OverviewCard(
isOwner: true,
total: data['all']?.length ?? 0,
active: data['online']?.length ?? 0,
inactive: data['offline']?.length ?? 0,
warning: data['warn']?.length ?? 0,
unused: data['not-use']?.length ?? 0,
showUnused: false,
);
}
},
),
],
),
),
),
),
);
}
}
);
}
void getOwnerAndJoinedDevices() async {
await apiServices.execute(context, () async {
devices = await apiServices.getDashBoardDevices().handleApiError();
List<DeviceWithAlias> publicDevices = [];
for (var device in devices) {
if (device.visibility == "PUBLIC") {
publicDevices.add(device);
}
}
getOwnerDeviceState(publicDevices);
checkSettingDevice(publicDevices);
getDeviceStatusAliasMap(publicDevices);
});
}
void getOwnerDeviceState(List<DeviceWithAlias> allDevices) async {
ownerDevicesState.clear();
ownerDevicesStatus.clear();
if (!mounted) return;
homeBloc.sinkOwnerDevicesStatus.add(ownerDevicesStatus);
int count = 0;
for (var device in allDevices) {
// if (device.isOwner != true) continue;
if (!mounted) return;
Map<String, dynamic> sensorMap = DeviceUtils.instance
.getDeviceSensors(context, device.status?.sensors ?? []);
if (device.state == 1 || device.state == 3) {
ownerDevicesStatus["state"] ??= [];
ownerDevicesStatus["state"]!.add(device);
if (!mounted) return;
homeBloc.sinkOwnerDevicesStatus.add(ownerDevicesStatus);
count++;
}
final noDataMessage = appLocalization(context).no_data_message;
if (sensorMap['sensorBattery'] != noDataMessage) {
if (double.parse(sensorMap['sensorBattery']) <= 20) {
ownerDevicesStatus['battery'] ??= [];
ownerDevicesStatus['battery']!.add(device);
if (!mounted) return;
homeBloc.sinkOwnerDevicesStatus.add(ownerDevicesStatus);
count++;
}
}
}
notificationCount = count;
if (!mounted) return;
homeBloc.sinkCountNotification.add(notificationCount);
}
void getDeviceStatusAliasMap(List<DeviceWithAlias> devices) {
allDevicesAliasMap.clear();
for (var key in ['all', 'online', 'offline', 'warning', 'not-use']) {
allDevicesAliasMap[key] = [];
}
for (DeviceWithAlias device in devices) {
allDevicesAliasMap['all']!.add(device);
if (device.state == 0 || device.state == 1) {
allDevicesAliasMap['online']!.add(device);
}
if (device.state == -1) {
allDevicesAliasMap['offline']!.add(device);
}
if (device.state == 1) {
allDevicesAliasMap['warning']!.add(device);
}
if (device.state == -2) {
allDevicesAliasMap['not-use']!.add(device);
}
}
homeBloc.sinkAllDevicesAliasMap.add(allDevicesAliasMap);
}
void checkSettingDevice(List<DeviceWithAlias> devices) async {
if (isFunctionCall) {
log("Ham check setting da duoc goi");

View File

@@ -7,7 +7,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:go_router/go_router.dart';
import 'package:badges/badges.dart' as badges;
import 'package:persistent_bottom_nav_bar/persistent_bottom_nav_bar.dart';
import 'package:persistent_bottom_nav_bar_v2/persistent_bottom_nav_bar_v2.dart';
import '../../product/utils/permission_handler.dart';
import '../../product/permission/notification_permission.dart';
@@ -147,79 +147,75 @@ class _MainScreenState extends State<MainScreen> with WidgetsBindingObserver {
WidgetsBinding.instance.removeObserver(this);
}
List<PersistentBottomNavBarItem> _navBarsItems() {
return [
PersistentBottomNavBarItem(
icon: IconConstants.instance.getMaterialIcon(Icons.home),
title: appLocalization(context).home_page_destination,
activeColorPrimary: Colors.blue,
inactiveColorPrimary: Colors.grey,
inactiveIcon:
IconConstants.instance.getMaterialIcon(Icons.home_outlined),
),
PersistentBottomNavBarItem(
icon: IconConstants.instance.getMaterialIcon(Icons.settings),
title: appLocalization(context).manager_page_destination,
activeColorPrimary: Colors.blue,
inactiveColorPrimary: Colors.grey,
inactiveIcon:
IconConstants.instance.getMaterialIcon(Icons.settings_outlined),
),
PersistentBottomNavBarItem(
icon: IconConstants.instance.getMaterialIcon(Icons.location_on),
title: appLocalization(context).map_page_destination,
activeColorPrimary: Colors.blue,
inactiveColorPrimary: Colors.grey,
inactiveIcon:
IconConstants.instance.getMaterialIcon(Icons.location_on_outlined),
),
PersistentBottomNavBarItem(
icon: IconConstants.instance.getMaterialIcon(Icons.history),
title: appLocalization(context).history_page_destination,
activeColorPrimary: Colors.blue,
inactiveColorPrimary: Colors.grey,
inactiveIcon:
IconConstants.instance.getMaterialIcon(Icons.history_outlined),
),
PersistentBottomNavBarItem(
icon: IconConstants.instance.getMaterialIcon(Icons.group),
title: appLocalization(context).group_page_destination,
activeColorPrimary: Colors.blue,
inactiveColorPrimary: Colors.grey,
inactiveIcon:
IconConstants.instance.getMaterialIcon(Icons.group_outlined),
),
];
}
List<Widget> _buildScreens() {
return [
BlocProvider(
child: HomeScreen(
persistentTabController: controller,
),
blocBuilder: () => HomeBloc(),
),
BlocProvider(
child: const DevicesManagerScreen(),
blocBuilder: () => DevicesManagerBloc()),
BlocProvider(
child: const MapScreen(),
blocBuilder: () => MapBloc(),
),
BlocProvider(
child: const DeviceLogsScreen(),
blocBuilder: () => DeviceLogsBloc(),
),
BlocProvider(
child: const InterFamilyScreen(),
blocBuilder: () => InterFamilyBloc(),
),
];
}
@override
Widget build(BuildContext context) {
List<PersistentTabConfig> tabs = [
PersistentTabConfig(
screen: BlocProvider(
child: const HomeScreen(),
blocBuilder: () => HomeBloc(),
),
item: ItemConfig(
icon: IconConstants.instance.getMaterialIcon(Icons.home),
title: appLocalization(context).home_page_destination,
inactiveIcon:
IconConstants.instance.getMaterialIcon(Icons.home_outlined),
iconSize: 30,
),
),
PersistentTabConfig(
screen: BlocProvider(
child: const DevicesManagerScreen(),
blocBuilder: () => DevicesManagerBloc(),
),
item: ItemConfig(
icon: IconConstants.instance.getMaterialIcon(Icons.settings),
title: appLocalization(context).manager_page_destination,
inactiveIcon:
IconConstants.instance.getMaterialIcon(Icons.settings_outlined),
iconSize: 30,
),
),
PersistentTabConfig(
screen: BlocProvider(
child: const MapScreen(),
blocBuilder: () => MapBloc(),
),
item: ItemConfig(
icon: IconConstants.instance.getMaterialIcon(Icons.location_on),
title: appLocalization(context).map_page_destination,
inactiveIcon: IconConstants.instance
.getMaterialIcon(Icons.location_on_outlined),
iconSize: 30,
),
),
PersistentTabConfig(
screen: BlocProvider(
child: const DeviceLogsScreen(),
blocBuilder: () => DeviceLogsBloc(),
),
item: ItemConfig(
icon: IconConstants.instance.getMaterialIcon(Icons.history),
title: appLocalization(context).history_page_destination,
inactiveIcon:
IconConstants.instance.getMaterialIcon(Icons.history_outlined),
iconSize: 30,
),
),
PersistentTabConfig(
screen: BlocProvider(
child: const InterFamilyScreen(),
blocBuilder: () => InterFamilyBloc(),
),
item: ItemConfig(
icon: IconConstants.instance.getMaterialIcon(Icons.group),
title: appLocalization(context).group_page_destination,
inactiveIcon:
IconConstants.instance.getMaterialIcon(Icons.group_outlined),
iconSize: 30,
),
),
];
return StreamBuilder<bool>(
stream: mainBloc.streamThemeMode,
initialData: isLight,
@@ -368,32 +364,27 @@ class _MainScreenState extends State<MainScreen> with WidgetsBindingObserver {
],
),
body: PersistentTabView(
context,
controller: controller,
screens: _buildScreens(),
items: _navBarsItems(),
handleAndroidBackButtonPress: true,
resizeToAvoidBottomInset: true,
stateManagement: false,
controller: controller,
tabs: tabs,
navBarBuilder: (navBarConfig) => Style6BottomNavBar(
navBarConfig: navBarConfig,
navBarDecoration: NavBarDecoration(
color: themeModeSnapshot.data! ? Colors.white : Colors.black,
borderRadius: BorderRadius.circular(context.mediumValue),
padding: const EdgeInsets.all(10)),
),
backgroundColor:
themeModeSnapshot.data! ? Colors.white : Colors.black,
decoration: NavBarDecoration(
borderRadius: BorderRadius.circular(30.0),
colorBehindNavBar:
themeModeSnapshot.data! ? Colors.white : Colors.black,
navBarOverlap: const NavBarOverlap.none(),
// margin: EdgeInsets.only(
// left: context.lowValue,
// bottom: context.dynamicHeight(0.02),
// right: context.lowValue),
screenTransitionAnimation: const ScreenTransitionAnimation(
curve: Curves.bounceInOut,
duration: Duration(milliseconds: 200),
),
animationSettings: const NavBarAnimationSettings(
navBarItemAnimation: ItemAnimationSettings(
duration: Duration(milliseconds: 200),
curve: Curves.bounceInOut,
),
screenTransitionAnimation: ScreenTransitionAnimationSettings(
animateTabTransition: true,
curve: Curves.bounceInOut,
duration: Duration(milliseconds: 200),
),
),
navBarStyle: NavBarStyle.style13,
),
);
},