我对此进行了测试并为我工作
主要飞镖:
import 'package:flutter/material.dart';
import 'package:local_notification/local_notification.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
@override
void initState() {
super.initState();
WidgetsBinding.instance?.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance?.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
var appInBackground = (state == AppLifecycleState.inactive);
if (appInBackground)
showNotificationMessage('App has gone into the background', 'FlutterApp');
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text(
'Testing app local notification\r\n'
' in background mode!',
style: TextStyle(fontSize: 28),
),
),
);
}
}
local_notification.dart:
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
//define this method in global scope not a class scope
void showNotificationMessage(String? description, String? title) {
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
var android = new AndroidInitializationSettings('@mipmap/ic_launcher');
var iOS = new IOSInitializationSettings();
var initSettings = new InitializationSettings(android: android, iOS: iOS);
flutterLocalNotificationsPlugin.initialize(initSettings,
onSelectNotification: null);
String groupKey = 'com.example.general-notification-channel';
var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
'general-notification-channel',
'general-notification-channel',
'general-notification-channel',
importance: Importance.max,
priority: Priority.high,
groupKey: groupKey,
// setAsGroupSummary: true
);
var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
NotificationDetails platformChannelSpecifics = new NotificationDetails(
android: androidPlatformChannelSpecifics,
iOS: iOSPlatformChannelSpecifics);
flutterLocalNotificationsPlugin.show(
0, title, description, platformChannelSpecifics);
}
pubspec.yaml:
name: local_notification
description: A new Flutter project.
publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.3
flutter_local_notifications: ^6.0.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true