我想使用这个包 https://pub.dev/packages/notification_permissions 做一个权限检查,我看到了里面的例子,但是我不能使用它并把它正确地放在我的项目上。
我只需要你的帮助,通过下面的示例正确使用它。
我的项目:
主文件==>
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:untitled/notification.dart';
import 'home_page.dart';
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
await initFcm();
runApp(const App());
}
class App extends StatefulWidget {
const App({Key? key}) : super(key: key);
@override
State<App> createState() => _AppState();
}
class _AppState extends State<App> {
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: HomePage(),
);
}
}
主页文件 ==>
import 'package:flutter/material.dart';
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home page'), centerTitle: true),
body: const Center(
child: ElevatedButton(
onPressed: null,
child: Text('Go to second page'),
),
),
);
}
}
通知文件==>
import 'dart:convert';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
Future<void> initFcm() async {
await Firebase.initializeApp();
var initializationSettingsAndroid = const AndroidInitializationSettings('@mipmap/ic_launcher');
var initializationSettingsIOS = const IOSInitializationSettings();
var initializationSettings = InitializationSettings(android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
flutterLocalNotificationsPlugin.initialize(initializationSettings);
await flutterLocalNotificationsPlugin.initialize(initializationSettings);
FirebaseMessaging.onMessage.listen((RemoteMessage? message) async {
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('channel.id', 'channel.name')),
payload: json.encode(message?.data),
);
}
});
}
依赖==>
firebase_core: ^1.22.0
firebase_messaging: ^13.0.1
flutter_local_notifications: ^9.9.1
使用权限处理程序包。
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Permission.notification.isDenied.then((value) {
if (value) {
Permission.notification.request();
}
});
await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
await initFcm();
runApp(const App());
}
除了Harsh Sureja的回答, 如果权限请求仍然没有出现,这应该对你有帮助:
https://github.com/Baseflow/flutter-permission-handler/issues/888#issuecomment-1223425033