2022年7月21日星期四

Local Notification Code

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

void main() {
runApp(
new MaterialApp(home: MyApp()),
);
}

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
late FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;

@override
initState() {
super.initState();
// initialise the plugin. app_icon needs to be a added as a drawable resource to the Android head project
// If you have skipped STEP 3 then change app_icon to @mipmap/ic_launcher
var initializationSettingsAndroid =
const AndroidInitializationSettings('icon');
var initializationSettingsIOS = IOSInitializationSettings();
var initializationSettings = InitializationSettings(
android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
//flutterLocalNotificationsPlugin.initialize(initializationSettings, onSelectNotification);
flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: onSelectNotification);
}

Future _showNotificationWithoutSound() async {
var androidPlatformChannelSpecifics = const AndroidNotificationDetails(
'channel id', 'channel name',
playSound: false, importance: Importance.max, priority: Priority.high);
var iOSPlatformChannelSpecifics =
IOSNotificationDetails(presentSound: false);
var platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics,
iOS: iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0,
'Title',
'Content',
platformChannelSpecifics,
payload: 'No_Sound',
);
}

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Plugin example app'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
RaisedButton(
onPressed: _showNotificationWithoutSound,
child: Text('Show Notification Without Sound'),
),
],
),
),
),
);
}

void onSelectNotification(String? payload) async { // when pressed the notification
showDialog(
context: context,
builder: (_) {
return new AlertDialog(
title: Text("PayLoad"),
content: Text("Payload : $payload"),
);
},
);
}
}

沒有留言:

發佈留言