84 lines
2.4 KiB
Dart
84 lines
2.4 KiB
Dart
|
import 'dart:async';
|
||
|
|
||
|
import 'package:flutter/material.dart';
|
||
|
import 'package:flutter_blue_plus_windows/flutter_blue_plus_windows.dart';
|
||
|
import 'package:shadcn_ui/shadcn_ui.dart';
|
||
|
import 'package:xiao_pet_tracker/home/view/home_page.dart';
|
||
|
import 'package:xiao_pet_tracker/l10n/l10n.dart';
|
||
|
import 'package:xiao_pet_tracker/screens/bluetooth_off_screen.dart';
|
||
|
|
||
|
class App extends StatefulWidget {
|
||
|
const App({super.key});
|
||
|
|
||
|
@override
|
||
|
State<App> createState() => _AppState();
|
||
|
}
|
||
|
|
||
|
class _AppState extends State<App> {
|
||
|
BluetoothAdapterState _adapterState = BluetoothAdapterState.unknown;
|
||
|
|
||
|
late StreamSubscription<BluetoothAdapterState> _adapterStateStateSubscription;
|
||
|
|
||
|
@override
|
||
|
void initState() {
|
||
|
super.initState();
|
||
|
_adapterStateStateSubscription =
|
||
|
FlutterBluePlus.adapterState.listen((state) {
|
||
|
_adapterState = state;
|
||
|
if (mounted) {
|
||
|
setState(() {});
|
||
|
}
|
||
|
});
|
||
|
}
|
||
|
|
||
|
@override
|
||
|
void dispose() {
|
||
|
_adapterStateStateSubscription.cancel();
|
||
|
super.dispose();
|
||
|
}
|
||
|
|
||
|
@override
|
||
|
Widget build(BuildContext context) {
|
||
|
Widget screen = _adapterState == BluetoothAdapterState.on
|
||
|
? const HomePage()
|
||
|
: BluetoothOffScreen(
|
||
|
adapterState: _adapterState,
|
||
|
);
|
||
|
|
||
|
return ShadApp.material(
|
||
|
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||
|
supportedLocales: AppLocalizations.supportedLocales,
|
||
|
navigatorObservers: [BluetoothAdapterStateObserver()],
|
||
|
home: screen,
|
||
|
);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// This observer listens for Bluetooth Off and dismisses the DeviceScreen
|
||
|
class BluetoothAdapterStateObserver extends NavigatorObserver {
|
||
|
StreamSubscription<BluetoothAdapterState>? _adapterStateSubscription;
|
||
|
|
||
|
@override
|
||
|
void didPush(Route route, Route? previousRoute) {
|
||
|
super.didPush(route, previousRoute);
|
||
|
if (route.settings.name == '/DeviceScreen') {
|
||
|
// Start listening to Bluetooth state changes when a new route is pushed
|
||
|
_adapterStateSubscription ??=
|
||
|
FlutterBluePlus.adapterState.listen((state) {
|
||
|
if (state != BluetoothAdapterState.on) {
|
||
|
// Pop the current route if Bluetooth is off
|
||
|
navigator?.pop();
|
||
|
}
|
||
|
});
|
||
|
}
|
||
|
}
|
||
|
|
||
|
@override
|
||
|
void didPop(Route route, Route? previousRoute) {
|
||
|
super.didPop(route, previousRoute);
|
||
|
// Cancel the subscription when the route is popped
|
||
|
_adapterStateSubscription?.cancel();
|
||
|
_adapterStateSubscription = null;
|
||
|
}
|
||
|
}
|