-
Notifications
You must be signed in to change notification settings - Fork 36
Description
我创建了一个新的flutter工程。flutter版本是3.19.6,并且按照文档引入插件并且配置了安卓的选项。我引入的插件是3.3.3版本。
这是我的main.dart文件内容:
import 'package:flutter/material.dart' hide Notification;
import 'package:push/push.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@OverRide
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// TRY THIS: Try running your application with "flutter run". You'll see
// the application has a purple toolbar. Then, without quitting the app,
// try changing the seedColor in the colorScheme below to Colors.green
// and then invoke "hot reload" (save your changes or press the "hot
// reload" button in a Flutter-supported IDE, or press "r" if you used
// the command line to start the app).
//
// Notice that the counter didn't reset back to zero; the application
// state is not lost during the reload. To reset the state, use hot
// restart instead.
//
// This works for code too, not just values: Most code changes can be
// tested with just a hot reload.
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@OverRide
State createState() => _MyHomePageState();
}
class _MyHomePageState extends State {
int _counter = 0;
String? _token = '';
// 存储所有的取消订阅函数
VoidCallback? _unsubscribeOnNewToken;
VoidCallback? _unsubscribeOnMessage;
VoidCallback? _unsubscribeOnBackgroundMessage;
VoidCallback? _unsubscribeOnNotificationTap;
// 状态变量,用于显示接收到的数据
Map<String?, Object?>? _notificationWhichLaunchedApp;
List _messagesReceived = [];
List _backgroundMessagesReceived = [];
List<Map<String?, Object?>> _tappedNotificationPayloads = [];
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@OverRide
void initState() {
super.initState();
_initializePushHandlers();
}
void _initializePushHandlers() {
// 监听新的token
_unsubscribeOnNewToken = Push.instance.addOnNewToken((token) {
print("Just got a new token: $token");
});
// 处理app被通知启动的情况
Push.instance.notificationTapWhichLaunchedAppFromTerminated.then((data) {
if (data == null) {
print("App was not launched by tapping a notification");
} else {
print('Notification tap launched app from terminated state:\n'
'Data: $data \n');
}
setState(() {
_notificationWhichLaunchedApp = data;
});
});
// 监听通知点击
_unsubscribeOnNotificationTap = Push.instance.addOnNotificationTap((data) {
print('Notification was tapped:\n'
'Data: $data \n');
setState(() {
_tappedNotificationPayloads.add(data);
});
});
// 监听前台消息 - 这会调用_sendAndroidReadyToProcessMessages()
_unsubscribeOnMessage = Push.instance.addOnMessage((message) {
print('RemoteMessage received while app is in foreground:\n'
'RemoteMessage.Notification: ${message.notification} \n'
' title: ${message.notification?.title.toString()}\n'
' body: ${message.notification?.body.toString()}\n'
'RemoteMessage.Data: ${message.data}');
setState(() {
_messagesReceived.add(message);
});
});
// 监听后台消息 - 这也会调用_sendAndroidReadyToProcessMessages()
_unsubscribeOnBackgroundMessage =
Push.instance.addOnBackgroundMessage((message) {
print('RemoteMessage received while app is in background:\n'
'RemoteMessage.Notification: ${message.notification} \n'
' title: ${message.notification?.title.toString()}\n'
' body: ${message.notification?.body.toString()}\n'
'RemoteMessage.Data: ${message.data}');
setState(() {
_backgroundMessagesReceived.add(message);
});
});
}
@OverRide
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// TRY THIS: Try changing the color here to a specific color (to
// Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
// change color while the other colors stay the same.
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
//
// TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
// action in the IDE, or press "p" in the console), to see the
// wireframe for each widget.
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
TextButton(
onPressed: () async {
String? token = await Push.instance.token;
setState(() {
_token = token;
});
},
child: const Text('获取token')
),
TextButton(
child: const Text("Delete token"),
onPressed: () async {
await Push.instance.deleteToken();
_token = "";
},
),
Text('token:$_token')
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
但是我App启动之后,并不会收到token, _unsubscribeOnNewToken = Push.instance.addOnNewToken((token) {
print("Just got a new token: $token");
}); 这个回调进不来。
如果我主动获取token,调用 String? token = await Push.instance.token; 会报如下的错误:
E/flutter (24930): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(channel-error, Unable to establish connection on channel: "dev.flutter.pigeon.push.PushHostApi.getToken"., null, null)
可以看到是通道的问题。
但是,我把同样的代码粘贴到你们插件源码的example中运行,并且把多余的文件都删除了!是能够获取到token的!并且点击获取token也不会报错!!!这是我修改之后的example文件截图:
插件的源码是做了什么额外的操作吗???
请帮忙看看这个问题,谢谢!