@@ -66,19 +66,54 @@ class _NoLocationDemoScreenState extends State<NoLocationDemoScreen> {
6666 String ? _pushSubscriptionId;
6767 bool _requestingPermission = false ;
6868 bool _sending = false ;
69+ late final OnPushSubscriptionChangeObserver _pushSubscriptionObserver;
70+ late final OnNotificationPermissionChangeObserver _permissionObserver;
6971
7072 bool get _isPlaceholderAppId =>
7173 _oneSignalAppId.toLowerCase ().startsWith ('your-' );
7274
7375 @override
7476 void initState () {
7577 super .initState ();
78+ _pushSubscriptionObserver = (state) {
79+ debugPrint ('Push subscription state: ${state .jsonRepresentation ()}' );
80+ if (! mounted) return ;
81+ setState (() {
82+ _pushSubscriptionId = state.current.id;
83+ });
84+ };
85+ _permissionObserver = (permission) {
86+ debugPrint ('Permission changed: $permission ' );
87+ if (! mounted) return ;
88+ setState (() {
89+ _hasNotificationPermission = permission;
90+ });
91+ };
92+ OneSignal .User .pushSubscription.addObserver (_pushSubscriptionObserver);
93+ OneSignal .Notifications .addPermissionObserver (_permissionObserver);
94+ _initializeOneSignal ();
95+ }
96+
97+ @override
98+ void dispose () {
99+ OneSignal .User .pushSubscription.removeObserver (_pushSubscriptionObserver);
100+ OneSignal .Notifications .removePermissionObserver (_permissionObserver);
101+ super .dispose ();
102+ }
103+
104+ Future <void > _initializeOneSignal () async {
76105 OneSignal .Debug .setLogLevel (OSLogLevel .verbose);
77- OneSignal .initialize (_oneSignalAppId);
78- _refreshPushState ();
106+
107+ try {
108+ await OneSignal .initialize (_oneSignalAppId);
109+ _refreshPushState ();
110+ } catch (error) {
111+ debugPrint ('OneSignal initialization failed: $error ' );
112+ }
79113 }
80114
81115 void _refreshPushState () {
116+ if (! mounted) return ;
82117 setState (() {
83118 _hasNotificationPermission = OneSignal .Notifications .permission;
84119 _pushSubscriptionId = OneSignal .User .pushSubscription.id;
@@ -92,6 +127,7 @@ class _NoLocationDemoScreenState extends State<NoLocationDemoScreen> {
92127
93128 try {
94129 final granted = await OneSignal .Notifications .requestPermission (false );
130+ if (! mounted) return ;
95131 setState (() {
96132 _hasNotificationPermission = granted;
97133 _pushSubscriptionId = OneSignal .User .pushSubscription.id;
0 commit comments