fix onDidReceiveNotificationResponse
This commit is contained in:
parent
691612a723
commit
e5b2edb670
File diff suppressed because one or more lines are too long
|
@ -1,109 +0,0 @@
|
|||
import 'package:firebase_core/firebase_core.dart';
|
||||
import 'package:firebase_messaging/firebase_messaging.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
import 'dart:convert';
|
||||
import 'dart:io' show Platform;
|
||||
|
||||
class PushNotificationService {
|
||||
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
|
||||
final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin =
|
||||
FlutterLocalNotificationsPlugin();
|
||||
static const String _channelId = 'visitRequest';
|
||||
static const String _channelName = 'Visitas';
|
||||
static const String _channelDescription = 'Solicitação de visita';
|
||||
|
||||
Future<void> initialize() async {
|
||||
var initializationSettingsAndroid =
|
||||
const AndroidInitializationSettings('ic_launcher');
|
||||
var initializationSettingsIOS = const DarwinInitializationSettings(
|
||||
requestAlertPermission: true,
|
||||
requestBadgePermission: true,
|
||||
requestSoundPermission: true,
|
||||
);
|
||||
var initializationSettings = InitializationSettings(
|
||||
android: initializationSettingsAndroid,
|
||||
iOS: initializationSettingsIOS,
|
||||
);
|
||||
await _flutterLocalNotificationsPlugin.initialize(initializationSettings);
|
||||
if (Platform.isAndroid) {
|
||||
var channel = const AndroidNotificationChannel(
|
||||
_channelId,
|
||||
_channelName,
|
||||
description: _channelDescription,
|
||||
importance: Importance.high,
|
||||
);
|
||||
await _flutterLocalNotificationsPlugin
|
||||
.resolvePlatformSpecificImplementation<
|
||||
AndroidFlutterLocalNotificationsPlugin>()
|
||||
?.createNotificationChannel(channel);
|
||||
}
|
||||
await Firebase.initializeApp();
|
||||
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
|
||||
FirebaseMessaging.onMessage.listen(_handleMessage);
|
||||
FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage);
|
||||
NotificationSettings settings = await _firebaseMessaging.requestPermission(
|
||||
alert: true,
|
||||
badge: true,
|
||||
sound: true,
|
||||
);
|
||||
debugPrint('User granted permission: ${settings.authorizationStatus}');
|
||||
}
|
||||
|
||||
void _handleMessage(RemoteMessage message) {
|
||||
RemoteNotification? notification = message.notification;
|
||||
AndroidNotification? android = message.notification?.android;
|
||||
Map<String, dynamic> data = message.data;
|
||||
|
||||
// Verifica se há um clickAction e se é um visit_request
|
||||
String? clickAction = data['clickAction'];
|
||||
if (clickAction != null && clickAction == "visit_request") {
|
||||
// Implementa a lógica específica para visit_request
|
||||
// Por exemplo, exibir uma notificação específica para visit_request
|
||||
if (notification != null && android != null) {
|
||||
var androidPlatformChannelSpecifics = const AndroidNotificationDetails(
|
||||
_channelId,
|
||||
_channelName,
|
||||
channelDescription: "Descrição específica para visit_request",
|
||||
importance: Importance.max,
|
||||
priority: Priority.high,
|
||||
);
|
||||
var platformChannelSpecifics = NotificationDetails(
|
||||
android: androidPlatformChannelSpecifics,
|
||||
);
|
||||
_flutterLocalNotificationsPlugin.show(
|
||||
notification.hashCode,
|
||||
"Título específico para visit_request",
|
||||
"Corpo específico para visit_request",
|
||||
platformChannelSpecifics,
|
||||
payload:
|
||||
"Dados adicionais que podem ser usados ao tocar na notificação",
|
||||
);
|
||||
}
|
||||
} else if (notification != null && android != null) {
|
||||
// Trata outras notificações como normalmente
|
||||
var androidPlatformChannelSpecifics = const AndroidNotificationDetails(
|
||||
_channelId,
|
||||
_channelName,
|
||||
channelDescription: _channelDescription,
|
||||
importance: Importance.max,
|
||||
priority: Priority.high,
|
||||
);
|
||||
var platformChannelSpecifics = NotificationDetails(
|
||||
android: androidPlatformChannelSpecifics,
|
||||
);
|
||||
_flutterLocalNotificationsPlugin.show(
|
||||
notification.hashCode,
|
||||
notification.title,
|
||||
notification.body,
|
||||
platformChannelSpecifics,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _firebaseMessagingBackgroundHandler(
|
||||
RemoteMessage message) async {
|
||||
await Firebase.initializeApp();
|
||||
print("Handling a background message: ${message.messageId}");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,158 @@
|
|||
import 'package:flutter/material.dart';
|
||||
import 'package:firebase_messaging/firebase_messaging.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
import 'package:f_r_e_hub/components/templates_components/visit_request_template_component/visit_request_template_component_widget.dart';
|
||||
import 'dart:io' show Platform;
|
||||
|
||||
import 'package:firebase_messaging/firebase_messaging.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class PushNotificationService {
|
||||
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
|
||||
Function(BuildContext)? onNotificationClick;
|
||||
|
||||
/// Inicializa o serviço de notificação push.
|
||||
Future<void> initialize() async {
|
||||
FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin =
|
||||
FlutterLocalNotificationsPlugin();
|
||||
await _requestPermissions();
|
||||
_configureLocalNotification(_flutterLocalNotificationsPlugin);
|
||||
_listenToForegroundMessages(_flutterLocalNotificationsPlugin);
|
||||
_handleMessageTap();
|
||||
_listenToBackgroundMessages();
|
||||
await _updateDeviceToken();
|
||||
}
|
||||
|
||||
void showCustomSheet(BuildContext context) {
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
builder: (BuildContext context) {
|
||||
return const VisitRequestTemplateComponentWidget(
|
||||
name: '', // Supondo que esses valores serão extraídos da mensagem
|
||||
image: '',
|
||||
message: '',
|
||||
reason: '',
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
void _configureLocalNotification(
|
||||
FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin) {
|
||||
var initializationSettingsAndroid =
|
||||
const AndroidInitializationSettings('mipmap/ic_launcher');
|
||||
var initializationSettingsIOS = const DarwinInitializationSettings(
|
||||
requestAlertPermission: true,
|
||||
requestBadgePermission: true,
|
||||
requestSoundPermission: true,
|
||||
);
|
||||
var initializationSettings = InitializationSettings(
|
||||
android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
|
||||
_flutterLocalNotificationsPlugin.initialize(initializationSettings,
|
||||
onDidReceiveNotificationResponse: (response) async {
|
||||
debugPrint('Notification tapped!');
|
||||
});
|
||||
}
|
||||
|
||||
/// Solicita permissões ao usuário para iOS.
|
||||
Future<void> _requestPermissions() async {
|
||||
NotificationSettings settings = await _firebaseMessaging.requestPermission(
|
||||
alert: true,
|
||||
badge: true,
|
||||
sound: true,
|
||||
);
|
||||
|
||||
if (settings.authorizationStatus == AuthorizationStatus.authorized) {
|
||||
debugPrint('User granted permission');
|
||||
} else {
|
||||
debugPrint('User declined or has not accepted permission');
|
||||
}
|
||||
}
|
||||
|
||||
void _listenToForegroundMessages(
|
||||
FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin) {
|
||||
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
|
||||
debugPrint('Got a message whilst in the foreground!');
|
||||
debugPrint('Message data: ${message.data}');
|
||||
RemoteNotification? notification = message.notification;
|
||||
AndroidNotification? android = message.notification?.android;
|
||||
if (notification != null && android != null) {
|
||||
_flutterLocalNotificationsPlugin.show(
|
||||
notification.hashCode,
|
||||
notification.title,
|
||||
notification.body,
|
||||
const NotificationDetails(
|
||||
android: AndroidNotificationDetails(
|
||||
'your_channel_id',
|
||||
'Your Channel Name',
|
||||
channelDescription: 'Your Channel Description',
|
||||
importance: Importance.max,
|
||||
priority: Priority.high,
|
||||
icon: 'mipmap/ic_launcher',
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Configura a ação ao tocar na notificação.
|
||||
void _handleMessageTap() {
|
||||
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
|
||||
debugPrint('Message clicked!');
|
||||
// Implementar ação ao tocar na notificação
|
||||
});
|
||||
}
|
||||
|
||||
/// Configura o ouvinte para mensagens em segundo plano.
|
||||
void _listenToBackgroundMessages() {
|
||||
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
|
||||
}
|
||||
|
||||
/// Atualiza o token do dispositivo e envia para o servidor, se necessário.
|
||||
Future<void> _updateDeviceToken() async {
|
||||
String? token = await _firebaseMessaging.getToken();
|
||||
debugPrint('Push Messaging token: $token');
|
||||
// Enviar token para o servidor
|
||||
}
|
||||
}
|
||||
|
||||
/// Manipula mensagens recebidas em segundo plano.
|
||||
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
|
||||
debugPrint('Handling a background message: ${message.messageId}');
|
||||
}
|
||||
|
||||
void _handleNotificationTap(
|
||||
NotificationResponse response, BuildContext context) {
|
||||
// Implementação para lidar com o toque na notificação
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
builder: (BuildContext context) {
|
||||
return const VisitRequestTemplateComponentWidget(
|
||||
name: '', // Supondo que esses valores serão extraídos da mensagem
|
||||
image: '',
|
||||
message: '',
|
||||
reason: '',
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
void _handleMessageOpenedApp(RemoteMessage message, BuildContext context) {
|
||||
// Mostra um modal ao invés de navegar para uma nova página
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
builder: (BuildContext context) {
|
||||
return const VisitRequestTemplateComponentWidget(
|
||||
name: '', // Supondo que esses valores serão extraídos da mensagem
|
||||
image: '',
|
||||
message: '',
|
||||
reason: '',
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
|
@ -295,7 +295,8 @@ class _VisitRequestTemplateComponentWidgetState
|
|||
.addToEnd(const SizedBox(width: 10.0)),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(24.0, 0.0, 24.0, 0.0),
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(
|
||||
24.0, 0.0, 24.0, 0.0),
|
||||
child: TextFormField(
|
||||
controller: _model.textController3,
|
||||
focusNode: _model.textFieldFocusNode3,
|
||||
|
@ -373,7 +374,8 @@ class _VisitRequestTemplateComponentWidgetState
|
|||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(24.0, 0.0, 24.0, 0.0),
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(
|
||||
24.0, 0.0, 24.0, 0.0),
|
||||
child: TextFormField(
|
||||
controller: _model.textController4,
|
||||
focusNode: _model.textFieldFocusNode4,
|
||||
|
@ -464,8 +466,8 @@ class _VisitRequestTemplateComponentWidgetState
|
|||
height: 40.0,
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(
|
||||
24.0, 0.0, 24.0, 0.0),
|
||||
iconPadding:
|
||||
const EdgeInsetsDirectional.fromSTEB(0.0, 0.0, 0.0, 0.0),
|
||||
iconPadding: const EdgeInsetsDirectional.fromSTEB(
|
||||
0.0, 0.0, 0.0, 0.0),
|
||||
color: FlutterFlowTheme.of(context).success,
|
||||
textStyle: FlutterFlowTheme.of(context)
|
||||
.titleSmall
|
||||
|
@ -498,8 +500,8 @@ class _VisitRequestTemplateComponentWidgetState
|
|||
height: 40.0,
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(
|
||||
24.0, 0.0, 24.0, 0.0),
|
||||
iconPadding:
|
||||
const EdgeInsetsDirectional.fromSTEB(0.0, 0.0, 0.0, 0.0),
|
||||
iconPadding: const EdgeInsetsDirectional.fromSTEB(
|
||||
0.0, 0.0, 0.0, 0.0),
|
||||
color: FlutterFlowTheme.of(context).error,
|
||||
textStyle: FlutterFlowTheme.of(context)
|
||||
.titleSmall
|
||||
|
|
|
@ -32,17 +32,17 @@ GoRouter createRouter(AppStateNotifier appStateNotifier) => GoRouter(
|
|||
initialLocation: '/',
|
||||
debugLogDiagnostics: true,
|
||||
refreshListenable: appStateNotifier,
|
||||
errorBuilder: (context, state) => appStateNotifier.showSplashImage
|
||||
? Builder(
|
||||
builder: (context) => Container(
|
||||
color: FlutterFlowTheme.of(context).primary,
|
||||
child: Image.asset(
|
||||
'assets/images/logo.svg',
|
||||
fit: BoxFit.cover,
|
||||
),
|
||||
),
|
||||
)
|
||||
: const PeopleOnThePropertyPageWidget(),
|
||||
// errorBuilder: (context, state) => appStateNotifier.showSplashImage
|
||||
// ? Builder(
|
||||
// builder: (context) => Container(
|
||||
// color: FlutterFlowTheme.of(context).primary,
|
||||
// child: Image.asset(
|
||||
// 'assets/images/logo.svg',
|
||||
// fit: BoxFit.cover,
|
||||
// ),
|
||||
// ),
|
||||
// )
|
||||
// : const PeopleOnThePropertyPageWidget(),
|
||||
routes: [
|
||||
// FFRoute(
|
||||
// name: '_initialize',
|
||||
|
@ -61,28 +61,8 @@ GoRouter createRouter(AppStateNotifier appStateNotifier) => GoRouter(
|
|||
// ),
|
||||
FFRoute(
|
||||
name: '_initialize',
|
||||
path: '/onBoardingPage',
|
||||
builder: (context, params) => LoginPageWidget(
|
||||
device: params.getParam(
|
||||
'device',
|
||||
ParamType.String,
|
||||
),
|
||||
),
|
||||
),
|
||||
FFRoute(
|
||||
name: 'LoginPage',
|
||||
path: '/loginPage',
|
||||
builder: (context, params) => LoginPageWidget(
|
||||
device: params.getParam(
|
||||
'device',
|
||||
ParamType.String,
|
||||
),
|
||||
),
|
||||
),
|
||||
FFRoute(
|
||||
name: 'ForgotPasswordPage',
|
||||
path: '/forgotPasswordPage',
|
||||
builder: (context, params) => const ForgotPasswordPageWidget(),
|
||||
path: '/',
|
||||
builder: (context, _) => const OnBoardingPageWidget(),
|
||||
),
|
||||
FFRoute(
|
||||
name: 'homePage',
|
||||
|
@ -153,7 +133,7 @@ GoRouter createRouter(AppStateNotifier appStateNotifier) => GoRouter(
|
|||
name: 'peopleOnThePropertyPage',
|
||||
path: '/peopleOnThePropertyPage',
|
||||
builder: (context, params) => const PeopleOnThePropertyPageWidget(),
|
||||
)
|
||||
),
|
||||
].map((r) => r.toRoute(appStateNotifier)).toList(),
|
||||
);
|
||||
|
||||
|
|
|
@ -1,4 +1,6 @@
|
|||
import 'package:f_r_e_hub/backend/api_requests/api_calls.dart';
|
||||
import 'package:f_r_e_hub/backend/push_notification/pushNotificationService.dart';
|
||||
import 'package:f_r_e_hub/components/templates_components/visit_request_template_component/visit_request_template_component_widget.dart';
|
||||
import 'package:firebase_core/firebase_core.dart';
|
||||
import 'package:firebase_messaging/firebase_messaging.dart';
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
|
@ -12,74 +14,27 @@ import 'flutter_flow/flutter_flow_util.dart';
|
|||
import 'flutter_flow/internationalization.dart';
|
||||
import 'package:firebase_analytics/firebase_analytics.dart';
|
||||
|
||||
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
|
||||
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
|
||||
FirebaseAnalytics analyticsInstance = FirebaseAnalytics.instance;
|
||||
analyticsInstance.logEvent(
|
||||
name: 'test_event',
|
||||
parameters: <String, Object>{
|
||||
'string': 'test',
|
||||
'int': 42,
|
||||
'long': 12345678910,
|
||||
'double': 42.0,
|
||||
'boolAsString': true.toString(),
|
||||
},
|
||||
);
|
||||
|
||||
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
|
||||
var initializationSettingsAndroid =
|
||||
const AndroidInitializationSettings('mipmap/ic_launcher');
|
||||
var initializationSettingsIOS = const DarwinInitializationSettings(
|
||||
requestAlertPermission: true,
|
||||
requestBadgePermission: true,
|
||||
requestSoundPermission: true,
|
||||
);
|
||||
var initializationSettings = InitializationSettings(
|
||||
android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
|
||||
await _flutterLocalNotificationsPlugin.initialize(initializationSettings);
|
||||
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
|
||||
RemoteNotification? notification = message.notification;
|
||||
AndroidNotification? android = message.notification?.android;
|
||||
if (notification != null && android != null) {
|
||||
_flutterLocalNotificationsPlugin.show(
|
||||
notification.hashCode,
|
||||
notification.title,
|
||||
notification.body,
|
||||
const NotificationDetails(
|
||||
android: AndroidNotificationDetails(
|
||||
'visitRequest',
|
||||
'Visitas',
|
||||
channelDescription: 'Solicitação de visita',
|
||||
importance: Importance.max,
|
||||
priority: Priority.high,
|
||||
icon: 'mipmap/ic_launcher',
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
GoRouter.optionURLReflectsImperativeAPIs = true;
|
||||
usePathUrlStrategy();
|
||||
await FlutterFlowTheme.initialize();
|
||||
await FFLocalizations.initialize();
|
||||
final appState = FFAppState();
|
||||
await appState.initializePersistedState();
|
||||
await initializeApp();
|
||||
runApp(ChangeNotifierProvider(
|
||||
create: (context) => appState,
|
||||
create: (context) => FFAppState(),
|
||||
child: const MyApp(),
|
||||
));
|
||||
}
|
||||
|
||||
// Inicialização do plugin de notificações locais
|
||||
FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin =
|
||||
FlutterLocalNotificationsPlugin();
|
||||
|
||||
// Manipulador de mensagens em segundo plano
|
||||
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
|
||||
// Certifique-se de inicializar o Firebase dentro do manipulador
|
||||
await Firebase.initializeApp();
|
||||
print("Handling a background message: ${message.messageId}");
|
||||
Future<void> initializeApp() async {
|
||||
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
|
||||
await FlutterFlowTheme.initialize();
|
||||
await FFLocalizations.initialize();
|
||||
final appState = FFAppState();
|
||||
await appState.initializePersistedState();
|
||||
GoRouter.optionURLReflectsImperativeAPIs = true;
|
||||
usePathUrlStrategy();
|
||||
final pushNotificationService = PushNotificationService();
|
||||
await pushNotificationService.initialize();
|
||||
}
|
||||
|
||||
class MyApp extends StatefulWidget {
|
||||
|
|
|
@ -1,4 +1,6 @@
|
|||
import 'package:f_r_e_hub/backend/push_notification/pushNotification.dart';
|
||||
// import 'package:f_r_e_hub/backend/push_notification/pushNotification.dart';
|
||||
import 'package:f_r_e_hub/backend/push_notification/pushNotificationService.dart';
|
||||
import 'package:f_r_e_hub/components/templates_components/visit_request_template_component/visit_request_template_component_widget.dart';
|
||||
import 'package:firebase_messaging/firebase_messaging.dart';
|
||||
|
||||
import '/components/organism_components/bottom_arrow_linked_locals_component/bottom_arrow_linked_locals_component_widget.dart';
|
||||
|
@ -33,8 +35,42 @@ class _HomePageWidgetState extends State<HomePageWidget> {
|
|||
super.initState();
|
||||
_model = createModel(context, () => HomePageModel());
|
||||
|
||||
// PushNotificationService().onNotificationClick = (context) {
|
||||
// showModalBottomSheet(
|
||||
// context: context,
|
||||
// isScrollControlled: true,
|
||||
// builder: (BuildContext context) {
|
||||
// return const VisitRequestTemplateComponentWidget(
|
||||
// name: '', // Supondo que esses valores serão extraídos da mensagem
|
||||
// image: '',
|
||||
// message: '',
|
||||
// reason: '',
|
||||
// );
|
||||
// },
|
||||
// );
|
||||
// };
|
||||
|
||||
// On page load action.
|
||||
SchedulerBinding.instance.addPostFrameCallback((_) async {
|
||||
FirebaseMessaging.onMessageOpenedApp.listen((message) {
|
||||
debugPrint('onMessageOpenedApp Test');
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (BuildContext context) {
|
||||
return Dialog(
|
||||
backgroundColor:
|
||||
Colors.transparent, // Faz o fundo do Dialog ser transparente
|
||||
child: VisitRequestTemplateComponentWidget(
|
||||
name: 'Nome Exemplo',
|
||||
reason: 'Motivo Exemplo',
|
||||
message: 'Mensagem Exemplo',
|
||||
image: 'URL da Imagem',
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
if (FFAppState().cliUUID == '') {
|
||||
showModalBottomSheet(
|
||||
isScrollControlled: true,
|
||||
|
|
Loading…
Reference in New Issue